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


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

 

最终效果

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM