如何在运行时使用 VueJS 3 中的自定义组件渲染 HTML?

One*_*yon 0 vue.js vuejs3

我目前正在尝试使用 Vue3 在运行时渲染 HTML(不,v-html这不足以满足我的需求,因为我有一个需要在 HTML 中渲染的自定义组件)。我该怎么做呢?

One*_*yon 6

事实证明,阻止这对我有用的是我的组件中的循环导入,所以我会自己回答它!在 Vue3 中,通过组件渲染任意 HTML(包括组件)要容易得多。下面是一些存根代码,展示了如何执行此操作的示例:

// IMPORTANT: you must import `compile` from this file! Standard Vue builds won't work
import { compile } from 'vue/dist/vue.esm-bundler.js'
// Include custom components that are embedded in your HTML here
import CustomComponent from './CustomComponent.vue'

export default {
  name: 'CustomContent',
  // The `content` prop should contain your HTML; you could alternately make it Markdown
  // or something and parse that in the `setup` method
  props: ['content'],
  components: {
    CustomComponent,
  },
  setup (props) {
    // Setup accepts a reactive `props` object and can return a render function, so this
    // functionally allows us to compile arbitrary HTML into Vue components
    return compile(props.content)
  },
}
Run Code Online (Sandbox Code Playgroud)

就是这样!主要注意事项均在注释中注明,您可以根据需要包含任意数量的自定义组件。只需注意自定义组件中的循环导入即可。;-)

(顺便说一句,您可以通过全局定义其中一个组件来解决循环导入问题,这就是我最终解决实际问题的方法。)