vue在v-html的html字符串中绑定事件

本文介绍了一种在Vue项目中,通过JavaScript事件捕获,实现动态绑定富文本元素事件的方法。具体步骤包括使用v-html展示富文本,并通过@click事件监听点击行为,进而获取并处理目标元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做项目,使用得vue作为基础框架。有这样一个需求,需要给返回来的富文本绑定事件,搜了一下众说纷纭。自己摸索了和总结出一套比较好用得方式。

 

利用JavaScript事件捕获,通过给使用v-html的标记绑定click事件,捕获到点击的标记。从而实现vue动态绑定dom元素事件的效果;

 

代码如下:

 

富文本数据:

"richTextContent": "<p class='testssss' data-innervalue='sadsadsa' data-value='{nasdlkashdashdkjsahdksd}'><span style=\"font-size: 14px;\"></span>Some Wi‑Fi networks are open and you can simply connect for internet access. Other Wi‑Fi networks are secure and require you to enter a password. Contact the Wi-Fi network&#39;s owner for the password.</p><p>To search for and connect with available Wi-Fi networks:</p><ol class=\" list-paddingleft-2\"><li><p>Swipe down from the top of your screen to open <strong>quick settings</strong> and then:</p></li><ul class=\" list-paddingleft-2\"><li><p>Android 9: Touch &amp; hold <img src=\"https://help.motorola.com/hc/images/global/qs_wifi_on_90.png\"/>.</p></li><li><p>Android 8: Touch <strong>Wi Fi &gt; More settings</strong></p></li><li><p>Android 7: Touch <strong>Wi Fi</strong>.</p></li></ul><li><p>Turn Wi-Fi on <img src=\"https://help.motorola.com/hc/images/global/slider_on.png\"/>.</p></li><li><p>Touch the Wi-Fi network you want to connect to.</p></li><li><p>If the network is a secure one, enter the password.</p></li></ol><p>Make sure you enter the password correctly. Touch <strong>Show password</strong> to see what you’re typing.</p><p>When your phone is connected, <img src=\"https://help.motorola.com/hc/images/global/i_wifi_min.png\"/> appears in the status bar. If the connection is poor, <img src=\"https://help.motorola.com/hc/images/global/i_wifi_poor.png\"/> appears in the status bar.</p>",

 

vue模板写法

<div class="richText" v-html="richTextContent" @click="test"></div>

 

script方法

test (event) {
   console.log(event.target.className) // testssss
   console.log(event.target.nodeName) // p
   if (event.target.nodeName === 'p' && event.target.className === 'testssss') {
     // 获取触发事件对象的属性
     alert('a')
   }    
}

 

最终效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值