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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM