Search code examples
vue.jsvuejs2vue-componentvue-loader

User editable Vue template


In my app, I have a template for things like Invoice, Email etc. I'd like the user to be able to edit these templates by dragging and dropping elements. I'm currently using vue-loader along with webpack to pre-compile my vue files into pure JS.

Is it possible to load a vue template from the database on the fly? I've seen this post but this isn't using vue-loader so I'm not sure how to override the template on my component via the code. Something like:

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

would be useful. Is this possible?

Edit: I've tried the following but I get an error 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>'
}

Solution

  • This would need to be modified to pass in the templates from your database, but this works in a very simple single file component. Obviously you will want to customize, but this demonstrates the concept.

    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)
    })