Vue $options.模板只能工作一次



我尝试构建一个动态Vue组件,在那里我传递一个模板字符串作为道具,并希望组件渲染它。

this.$options.template = this.htmlString;

这似乎工作得很好,直到我试图改变模板。当htmlString改变时,我无法获得组件渲染。有办法做到这一点吗?

我也尝试了render功能和Vue.compile,但我真的不知道如何使用它们。这会抛出错误:

render(createElement) {
return Vue.compile(this.htmlString).render(createElement);
}

Vue 2.6

在Vue 2中,compile返回一个具有render方法的对象。由于Vue组件是一个应该具有rendertemplate属性的对象,因此对象被createElement标识为组件,并且可以直接传递给它:

render(createElement) {
return createElement(Vue.compile(this.htmlString));
}

compile可以移动到一个计算,以跳过不必要的调用:

computed: {
HtmlComp() {
return Vue.compile(this.htmlString);
}
},
render(createElement) {
return createElement(this.HtmlComp);
}

同样适用于Vue 3,根据API的变化进行了调整。

最新更新