How to make Vue js directive working in an appended html element

后端 未结 3 1066
轮回少年
轮回少年 2020-12-29 07:58

I have a Vue directive added in an appended html element like v-on directive but it\'s not working on my end. Basically I want to know the equivalent of .on() in jquery.

3条回答
  •  时光说笑
    2020-12-29 08:37

    "Vue.js compilation happens when you instantiate/mount the root instance. It doesn't detect new DOM being injected unless it is a result of a directive (e.g. v-repeat, v-partial will dynamically create new DOM fragments)." https://github.com/vuejs/Discussion/issues/77

    You have to compile your newly added element like this:

    html:


    JavaScript

    new Vue({
        el: '#app',
        data: {
            sampleElement: ''
        },
        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');
            }
        }
    });
    

    See this working Fiddle on Firefox: http://jsfiddle.net/chrislandeza/syewmx4e/

    Update

    $compile has been removed on Vue 2.x

    I've seen people suggesting Vue.compile or

    var tmp = Vue.extend({ 
        template: 'Content'
    })
    new tmp().$mount(' id or refs ')
    

    But those 2 does not behave like the old $compile.

提交回复
热议问题