我想向组件发送一个“模板”道具然后渲染它。如果我发送一个纯 HTML 它可以工作,但是如果我发送一个 Vuetify 标签,比如<v-btn>test</v-btn>模板不会被编译。
我知道我不应该通过道具传递模板,但这是一个特殊情况:父组件充当“模板构建器”,子组件充当“结果查看器”,所以我必须将创建的模板传递给孩子,以便它可以编译并显示它。
这是我一直在尝试的:
主程序
import Vue from 'vue'
import App from './App.vue'
// Some imports here ...
import vuetify from './plugins/vuetify';
new Vue({
vuetify,
render: h => h(App)
}).$mount('#app')
应用程序.vue
<script
import Vue from 'vue'
// eslint-disable-next-line
var staticRenderFns = [];
var dynamic = {
props: ['template'],
data: () => ({
templateRender: null,
}),
render(h) {
if (!this.templateRender) {
return h('div', 'loading...');
} else { // If there is a template, I'll show it
return this.templateRender();
}
},
watch: {
// Every time the template prop changes, I recompile it to update the DOM
template:{
immediate: true, // makes the watcher fire on first render, too.
handler() {
var res = Vue.compile(this.template);
this.templateRender = res.render;
// staticRenderFns belong into $options,
// appearantly
this.$options.staticRenderFns = []
// clean the cache of static elements
// this is a cache with the results from the staticRenderFns
this._staticTrees = []
// Fill it with the new staticRenderFns
for (var i in res.staticRenderFns) {
//staticRenderFns.push(res.staticRenderFns[i]);
this.$options.staticRenderFns.push(res.staticRenderFns[i])
}
}
}
},
}
export default {
name: 'App',
data: () => ({
template:`
<v-row>
<v-col>
<v-btn class="pa-2 primary white--text">Test</v-btn>
</v-col>
<v-col>
<v-btn class="pa-2 primary white--text">Test</v-btn>
</v-col>
<v-col>
<v-btn class="pa-2 primary white--text">Test</v-btn>
</v-col>
</v-row>
`,
}),
components:{
dynamic,
},
FFIVE
相关分类