runtime template in vuejs

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

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

我们知道v-html有点接近我们的需求,可是v-html仅仅能够展示标准的html元素,不能包含vue组件的元素。

搜索了很多文章结合自己的探索,有两个方式:

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编译器

posted @ 2019-10-07 21:46  世有因果知因求果  阅读(870)  评论(0编辑  收藏  举报