Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

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.

like image 360
Darwin Luague Avatar asked May 30 '15 12:05

Darwin Luague


People also ask

How do you link VueJS file to HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.

Can you use Vue in HTML?

You can use Vue to build standard Web Components that can be embedded in any HTML page, regardless of how they are rendered.

How do I reference an element in Vue?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.


1 Answers

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

like image 118
Chris Landeza Avatar answered Sep 21 '22 18:09

Chris Landeza