如何在Vue中的“ v-html”上绑定点击事件 [英] How to bind a click event on “v-html” in Vue
本文介绍了如何在Vue中的“ v-html”上绑定点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在jsfiddle中有一个简单的示例,如示例中所述,我想通过v-html插入元素,然后将事件绑定到insert元素中。除了通过这种方式添加id操作dom之外,还有更好的方法吗?
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>'
}
})
推荐答案
您可以在<上添加 ref code> div ,并像常规JavaScript一样使用其子元素进行操作。例如,您可以为 mounted
挂钩内的链接设置事件监听器:
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>
这篇关于如何在Vue中的“ v-html”上绑定点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文