我在jsfiddle中有一个简单的例子,如示例中所述,我想通过v-html插入元素,然后在insert元素中绑定事件。除了以这种方式添加id操作,还有更好的方法吗?
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>'
}
})
答案 0 :(得分:6)
您可以在div
上添加ref,并像常规JavaScript一样使用其子元素。例如,您可以为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);
})
}
})
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div v-html="link" ref="mydiv"></div> <!-- notice 'ref' -->
</div>
&#13;