如果你需要在使用v-html渲染的内容上绑定事件,你可以使用事件委托。事件委托是一种处理事件的方式,它将事件监听器绑定到一个父元素,而不是每个子元素单独绑定。
<template>
<div v-html="rawHtml" @click="handleClick"></div>
</template>
<script>
export default {
data() {
return {
rawHtml: '<button class="my-button">Click Me</button>'
};
},
methods: {
handleClick(event) {
const button = event.target.closest('.my-button');
if (button) {
// 执行按钮点击的操作
alert('Button clicked!');
}
}
}
};
</script>