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

相關文章
相關標籤/搜索