【问题标题】:How to render Vue component which is coming from an html field of my database?如何渲染来自我数据库的 html 字段的 Vue 组件?
【发布时间】:2021-05-16 02:52:40
【问题描述】:

承认,我的数据库中有一个“内容”字段,我在其中存储了一个组件以及要显示的数据。 如何渲染这个组件?

我知道 v-html 可以渲染 html,但它不理解组件。

// My data coming from database:
// data.content = "<w-image slug="my-image-slug"></w-image>"

<template>
   <div v-html="data.content"></div> <!-- just show the html output -->
</template>
<script>
import WImage from '@/Components/Widgets/Image.vue'
...
export default {
   props:{
        data : Object,
        ...
    },
    components: {
        WImage,
        ...
    },
}
</script>

我猜这是不可能的,因为它没有编译代码。 但是,我通常对这样做的可能性感到惊讶......
我给它一个机会。

【问题讨论】:

    标签: vue.js dynamic components


    【解决方案1】:

    根据您提供的信息,我可以想象一个解决方案,如下所示:

    Vue.component("WImage", {
      props: ['slug'],
      template: `
        <div>{{ slug }}</div>
      `
    })
    
    new Vue({
      el: "#app",
      data() {
        return {
          htmlstring: "<w-image slug='my-image-slug'></w-image>"
        }
      },
      render(h) {
        return h({
          template: `<div>${ this.htmlstring }</div>`
        })
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"></div>

    如果您事先知道可能的组件,那么您可以将它们注册/动态导入到处理所有HTML 字符串的组件中。使用render 函数通过将template 传递给它一个组件对象来呈现HTML 字符串。

    您需要full build of Vue 来执行此技巧 - 正常构建不会即时编译模板,因此无法正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2023-03-23
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2018-12-03
      相关资源
      最近更新 更多