Reputation: 561
I have a simple example in jsfiddle, as described in the example, I want to insert the element via v-html and then bind the event in the insert element. In addition to adding id operation dom this way, is there a better way?
https://jsfiddle.net/limingyang/bnLmx1en/1/
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div v-html="link"></div>
</div>
var app = new Vue({
el: '#app',
data: {
link: '<a href="javascript:void(0)">click me</a>'
}
})
Upvotes: 22
Views: 19382
Reputation: 23
For people having problem with @tony19 solution:
If your v-html is dynamically updated and you want to do something on the element you have to use
Vue.nextTick(() => {});
Because you have to wait for the DOM to create the element before accessing its child nodes.
Upvotes: 2
Reputation: 18156
You can add a ref on your div
, and operate with its children elements like you do in regular JavaScript. For example, you can set an event listener for a link inside mounted
hook:
var app = new Vue({
el: '#app',
data: {
link: '<a href="#">click me</a>'
},
mounted() {
this.$refs['mydiv'].firstChild.addEventListener('click', function(event) {
event.preventDefault();
console.log('clicked: ', event.target);
})
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div v-html="link" ref="mydiv"></div> <!-- notice 'ref' -->
</div>
Upvotes: 26