vue.js - 包含 Vue 组件的一串 HTML 的 Nuxt 渲染函数

标签 vue.js dom render 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>'

注意它包含一个 Vue 组件 <site-banner>上面有一些 Prop (image Prop 是一个 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 中有效,除了它不会实际渲染 this.html 中的 Vue 组件。 , 它只是将它们作为 HTML 放在页面上。

那么我如何在 Nuxt 中执行此操作?我想从服务器获取一串 HTML,并将其呈现在页面上,并将任何已注册的 Vue 组件转换为适当的成熟 Vue 组件。基本上是一个“VueifyThis(html)”工厂。

最佳答案

感谢 Nuxt 团队的 Jonas Galvez,通过 oTechie,这是最有效且最干净的方法.

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 <component-name> works
            config.resolve.alias["vue$"] = "vue/dist/vue.esm.js"
        }
    }

关于vue.js - 包含 Vue 组件的一串 HTML 的 Nuxt 渲染函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56013561/

相关文章:

php - 公理 : Network Error with Vuejs

javascript - Vue.js 中的条件逻辑

javascript - Masonry.js 不应用布局

reactjs - 使用 hooks 进行两次 React 渲染

javascript - 使用 Promise 时 Render 不返回任何内容

javascript - 通过输入进行搜索

javascript - 有没有办法批量套用多个CSS样式,避免多次回流?

javascript - 如何查询以相同ID开头的多个元素,然后检查输入是否发生变化

javascript - AngularJS,指令元素为空

ruby-on-rails-4 - Rails 实例变量未传递给带有 "Render"的 View