首页 > Web开发 > 详细

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

时间:2019-12-19 16:11:04      阅读:656      评论:0      收藏:0      [点我收藏+]

最近做项目,使用得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‘)
   }    
}

 

最终效果

技术分享图片

 

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

原文:https://www.cnblogs.com/wangweizhang/p/12067700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!