用户可编辑的Vue模板

时间:2017-03-07 19:21:21

标签: vue.js vuejs2 vue-component vue-loader

在我的应用程序中,我有一个模板,用于发票,电子邮件等。我希望用户能够通过拖放元素来编辑这些模板。我目前正在使用vue-loaderwebpack将我的vue文件预编译为纯JS。

是否可以动态加载数据库中的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>'
}

1 个答案:

答案 0 :(得分: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)
})