最近项目中遇到需求,抓取原字符串信息中的手机号码,添加高亮以及添加点击复制功能,因为是字符串中拼接了html元素,vue默认依然显示为字符串不进行渲染,所以用到了v-html这个指令,但遇到新的问题,字符串中拼接元素内加的事件渲染出来并不会调用,查原因说是v-html中的标签不能调用vue method中的方法
下面附代码以及实现方案:
v-html中绑定的是这种形式:
for (var i = 0; i < phoneNums.length; i++) {
var temp = phoneNums[i]
str = str.replace(phoneNums[i], '<a href="tel:' + temp + '" class="copy phone-num" style=" text-decoration: underline;color: #2878FF;">' + temp + '</a>');
}
是字符串中拼接的a标签
解决思路是,首先事件绑定到父元素上
<div v-html="item.name" @click="copyPhone">
然后父元素点击时,进行判断,判断点击事件是否发生在希望点击的子元素上,如果是则进行相应的逻辑操作
copyPhone(event) {
if (event.target.className === 'copy phone-num') {
console.log(event.target.innerText)
let phone = event.target.innerText
const clipboard = new ClipboardJS('.copy', {
text: function(trigger) {
return phone
}
});
clipboard.on('success', () => {
this.$toast.success('复制成功');
});
clipboard.on('error', () => {
this.$toast.success('复制失败');
});
}
}