Nuxt渲染函数,用于包含Vue组件的HTML字符串

vue.js Vue.js

西门

2020-03-23

我正在为Nuxt解决这个问题

WIP的Codesandbox无法使用:https://codesandbox.io/s/zw26v3940m

好的,所以我将WordPress作为CMS,它正在输出一堆HTML。HTML的示例如下所示:

'<h2>A heading tag</h2>
<site-banner image="{}" id="123">Slot text here</site-banner>
<p>some text</p>'

请注意,它包含一个<site-banner>带有一些道具的Vue组件(该image道具是我为了简洁而省略的JSON对象)。该组件已在全球注册。

我有一个我们编写的组件,该组件<wp-content>在Vue中很好用,但在Nuxt中不起作用。注意这两个渲染函数,一个是Vue的,另一个是Nuxt的(显然,这是出于示例的原因,我不会同时使用两者)。

export default {
    props: {
        html: {
            type: String,
            default: ""
        }
    },
    render(h, context) {
        // Worked great in Vue
        return h({ template: this.html })
    }      
    render(createElement, context) {
        // Kind of works in Nuxt, but doesn't render Vue components at all
        return createElement("div", { domProps: { innerHTML: this.html } })
    } 
}

因此,最后一个渲染函数在Nuxt中可用,除了它实际上不会在中渲染Vue组件外this.html,它只是将它们作为HTML放置在页面上。

So how do I do this in Nuxt? I want to take a string of HTML from the server, and render it on the page, and turn any registered Vue components into proper full-blown Vue components. Basically a little "VueifyThis(html)" factory.

第2701篇《Nuxt渲染函数,用于包含Vue组件的HTML字符串》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
LGil 2020.03.23

我对您的codeandbox进行了一些更改。似乎现在可以工作https://codesandbox.io/s/q9wl8ry6q9

我更改的东西无效:

  1. 模板在当前版本的Vue中只能具有一个根元素
  2. v-bind仅接受变量,但您传入一个字符串。
小胖猪猪 2020.03.23

如果您使用v-html指令呈现html?

喜欢:

<div v-html="html"></div>

我认为它将做得到。

蛋蛋Itachi 2020.03.23

这是关于codeandbox的解决方案:https ://codesandbox.io/s/wpcontent-j43sp

要点是将动态组件包装<div>dynamicComponent()模板中的一个HTML标记中(因为它只有一个根元素),并且它来自Wordpress,因此源字符串本身可以具有任意数量的顶级元素。

而且该WpContent组件必须导入。

十三Harry 2020.03.23

这是最有效的方法,也是最干净的方法,这要归功于Nuxt团队通过oTechie提供的Jonas Galvez

export default {
  props: {
    html: {
      type: String,
      default: ""
    }
  },
  render(h) {
    return h({
      template: `<div>${this.html}</div>`
    });
  }
};

然后在您的nuxt.config.js文件中:

    build: {
        extend(config, ctx) {
            // Include the compiler version of Vue so that wp-content works
            config.resolve.alias["vue$"] = "vue/dist/vue.esm.js"
        }
    }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android