16

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 Answers 3

20

"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:

<div id="app">
    <button v-on="click: addNewElement()">Add Element</button> 
    <br />
</div>

JavaScript

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Alexandros Because I was using raw github on my fiddle's external resource. I just fixed that and updated my answer. Sorry for that.
Sadly, it does not work any more with new vue version. Firstly, syntax has changed for click event. Secondly, there's no "$compile" function any more (probably renamed). If you remove compile and fix syntax, add button works but new buttons do nothing.
11

For Vue 2.x, the new solution is referenced here in the doc : https://v2.vuejs.org/v2/api/#vm-mount (see 'Example').

Custom example :

var MyComponent = Vue.extend({
  template: '<div v-on:click="world">Hello!</div>',
  methods : {
    world : function() {
      console.log('world')
    }
  }
})
 
var component = new MyComponent().$mount()
document.getElementById('app').appendChild(component.$el)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app"></div>

Works like a charm!

Comments

0

You need to register the html as a template of the component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.