runtime template in vuejs

在使用vuejs开发的过程当中,有时候咱们须要动态模板的场景,也就是说模板并非静态定义好的,而是动态变化的。html

好比在作一个所见所得编辑器时,编辑人员可能时刻须要调整他设计的页面内容,而若是页面内容包含vue组件的话,这时若是须要实时预览效果的话,就必需要解决动态模板如何实时编译运行的问题。vue

咱们知道v-html有点接近咱们的需求,但是v-html仅仅可以展现标准的html元素,不能包含vue组件的元素。git

搜索了不少文章结合本身的探索,有两个方式:github

1. 直接使用vuejs的render函数

export default {
        props: [ 'tpl'],
        components: { VueCompA, VueCompB },
        created(){
            try{
                var res = Vue.compile(this.tpl,{}, this)
                this.$options.render = res.render
                this.$options.staticRenderFns = res.staticRenderFns
            }
            catch (err){
                console.log(err)
            }
        }
    };

这样经过如下的调用便可:编辑器

<templatepreview :tpl="flyingTemplate"></templatepreview>

 

2.使用现成的模块

参考v-https://github.com/alexjoverm/v-runtime-template-template函数

须要注意的是以上方案可以工做的前提是Vue必须自带compiler编译器this

相关文章
相关标签/搜索