Vue.js 2.0 this. $ Compile

How can you compile an HTML string into a template in a component method? It is possible in Vue 1, as in this jsfiddle

new Vue({
    el: '#app',
    data: {
        sampleElement: '<button v-on="click: test()">Test</button>'

    },
    methods:{
        addNewElement: function(){

           var element = $('#app').append(this.sampleElement);
            /* compile the new content so that vue can read it */
           this.$compile(element.get(0));
        },
        test: function(){
           alert('Test');
        }
    }
});

How can you do this in Vue 2?

+2
source share
1 answer

This is no longer possible, however Vue 2data-driven, so you should not try to influence the DOM manually at all, instead you should bind elements to the underlying data in your view model. With this in mind, your example will need to be rewritten. First, start by creating an element component:

Vue.component('my-button', {
  template: '<button v-on:click="test()">{{text}}</button>',
  props: ['text'],
  methods: {
    test() {
      alert('Test');
    }
  }
});

Then you can create your main view model and add your button component with v-for:

Markup:

  <button v-on:click="addNewElement()">Add Element</button>
  <my-button v-for="button in buttons" :text="button"></my-button>

View Model:

new Vue({
  el: '#app',
  methods: {
    addNewElement: function() {
       this.buttons.push('Test');
    }
  },
  data: {
    buttons: []
  }
});

, , .

JSFiddle: http://jsfiddle.net/10q9je5a/

, different components :is, Vue , :

:

<div id="app">
  <button v-on:click="addNewElement()">Add Element</button>
  <div :is="element.component" v-for="element in elements" v-bind="element.props"></div>
</div>

:

new Vue({
  el: '#app',
  methods: {
    addNewElement: function() {
       this.elements.push({component: 'my-button', props: {text: 'Test'}});
    }
  },
  data: {
    elements: []
  }
});

JSFiddle : http://jsfiddle.net/cxo5eto0/

+1

Source: https://habr.com/ru/post/1670146/


All Articles