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

Dre*_*ker 9 dom render vue.js nuxt.js

我正在为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>'
Run Code Online (Sandbox Code Playgroud)

请注意,它包含一个<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 } })
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

那么我如何在Nuxt中做到这一点?我想从服务器中获取一串HTML,并将其呈现在页面上,并将所有已注册的Vue组件转换为适当的成熟Vue组件。基本上是一些“ VueifyThis(html)”工厂。

Dre*_*ker 6

这是最有效且最干净的方法,感谢 Nuxt 团队的 Jonas Galvez 通过oTechie提供的帮助。

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

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

    build: {
        extend(config, ctx) {
            // Include the compiler version of Vue so that <component-name> works
            config.resolve.alias["vue$"] = "vue/dist/vue.esm.js"
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你使用v-html指令来渲染 html?

喜欢:

<div v-html="html"></div>
Run Code Online (Sandbox Code Playgroud)

我认为它会完成这项工作。