2017-03-07 100 views
2

在我的應用程序中,我有一個模板,如發票,電子郵件等。我希望用戶能夠通過拖放元素來編輯這些模板。我目前使用vue-loader以及webpack將我的vue文件預編譯爲純JS。用戶可編輯Vue模板

是否可以從數據庫中隨時加載vue模板?我見過this後,但這不是vue-loader所以我不知道如何通過代碼覆蓋我的組件上的模板。例如:

created: function() { 
    this.$template = '<html><p>Loaded from the DB!</p></html>' 
} 

將是有用的。這可能嗎?

編輯:我試過以下,但我得到一個錯誤Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

created: function() { 
    document.body.innerHTML = '<html><p>I AM FROM THE DB {{total}}</p></html>' 
} 
+0

如果您使用的是單文件組件(.vue )fi你可能做的,恐怕這是不可能的。更好的方法是建立API.Vue,在客戶端,沒有提供任何模塊直接與數據庫進行通信,運行時版本也不允許你直接使用模板屬性到vue實例中。 –

+0

@BelminBedak該死的,但感謝你的反響。我剛剛閱讀了「異步組件」(https://vuejs.org/v2/guide/components.html#Async-Components)。你認爲他們可以被利用嗎(我還在讀)?看起來我可以聲明組件,然後在從數據庫加載時解析它... – webnoob

+0

讓我們首先明確您正在使用的數據庫?是Mongo,Firebase還是其他? –

回答

3

這將需要進行修改,從數據庫模板通過,但該作品在一個非常簡單的單個文件組件。顯然你會想要自定義,但是這表明了這個概念。

Dynamic.vue

<script> 
    export default { 
     props:["template"], 
     data(){ 
      return { 
       message:"hello" 
      } 
     }, 
     created(){ 
      this.$options.template = this.template 
     } 
    } 
</script> 

App.vue

<template> 
    <div> 
     <dynamic 
     v-for="template, index of templates" 
     :template="template" :key="index"> 
    </dynamic> 
    </div> 
</template> 

<script> 
    import Vue from "vue" 
    import Dynamic from "./Dynamic.vue" 

    export default { 
    name: 'app', 
    data() { 
     return { 
     templates: [ 
      "<h1>{{message}}</h1>", 
      "<h4>{{message}}</h4>" 
     ] 
     } 
    }, 
    components:{ 
     Dynamic 
    } 
    } 
</script> 

main.js

import Vue from 'vue' 
import App from './App.vue' 

new Vue({ 
    el: '#app', 
    render: h => h(App) 
}) 
+0

這需要僅運行時版本才能工作,而我沒有使用該版本。我可以在我的Webpack配置中添加'vue':'vue/dist/vue.common.js'到這個解決方案。使用運行時版本的唯一缺點是vue模板的編譯時間? – webnoob

+0

@webnoob我相信,以及額外的腳本下載。 – Bert

+0

那麼,我認爲它應該在初始下載後緩存(並且我的應用程序是基於服務的,所以最初的額外第二次下載不是問題),我認爲這是一種交易。我會沿着這條路走下去。非常感謝你的協助。 – webnoob