Vue 阻止事件冒泡
生活随笔
收集整理的這篇文章主要介紹了
Vue 阻止事件冒泡
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
轉(zhuǎn)載自??Vue2學(xué)習(xí)筆記:事件對象、事件冒泡、默認(rèn)行為
1.事情對象
<!DOCTYPE html> <html> <head><title></title><meta charset="utf-8"><script src="http://unpkg.com/vue/dist/vue.js"></script><script type="text/javascript">window.onload = function(){var vm = new Vue({el:'#box',methods:{show:function(event){console.log(event); //event 這個就是事件對象了 }}});}</script> </head> <body><div id="box"><input type="button" value="按鈕" @click="show($event)"> </div> </body> </html>通過show($event)把事件對象傳到方法里
?
2.事件冒泡
<!DOCTYPE html> <html> <head><title></title><meta charset="utf-8"><script src="http://unpkg.com/vue/dist/vue.js"></script><script type="text/javascript">window.onload = function(){var vm = new Vue({el:'#box',methods:{show:function(){alert(1);},show1:function(){alert(2);}}});}</script> </head> <body><div id="box"><div @click="show1()"><input type="button" value="按鈕" @click="show()"> </div></div> </body> </html>點(diǎn)擊按鈕的話他會,執(zhí)行show ,show1方法,依次彈出1,2。
?
怎么來阻止
<1>?利用我們上面講過的event對象: ?event.cancelBubble =?true; ? //這種就阻止了
<!DOCTYPE html> <html> <head><title></title><meta charset="utf-8"><script src="http://unpkg.com/vue/dist/vue.js"></script><script type="text/javascript">window.onload = function(){var vm = new Vue({el:'#box',methods:{show:function(event){alert(1);event.cancelBubble = true;},show1:function(){alert(2);}}});}</script> </head> <body><div id="box"><div @click="show1()"><input type="button" value="按鈕" @click="show($event)"> </div></div> </body> </html>?
<2>利用vue的方法阻止冒泡:給HTML元素綁定click事件的時候,改為@click.stop="show()"
<!DOCTYPE html> <html> <head><title></title><meta charset="utf-8"><script src="http://unpkg.com/vue/dist/vue.js"></script><script type="text/javascript">window.onload = function(){var vm = new Vue({el:'#box',methods:{show:function(event){alert(1);//event.cancelBubble = true; },show1:function(){alert(2);}}});}</script> </head> <body><div id="box"><div @click="show1()"><input type="button" value="按鈕" @click.stop="show()"> </div></div> </body> </html>?
3.默認(rèn)行為
比如contextmenu右鍵菜單
<!DOCTYPE html> <html> <head><title></title><meta charset="utf-8"><!-- // <script src="vue.js"></script> --><script src="http://unpkg.com/vue/dist/vue.js"></script><script type="text/javascript">window.onload = function(){var vm = new Vue({el:'#box',methods:{show:function(){alert(1);},show1:function(){alert(2);}}});}</script> </head> <body><div id="box"><input type="button" value="按鈕" @contextmenu="show()"> <input type="button" value="按鈕1" @contextmenu.prevent="show1()"> <p>//按鈕右擊點(diǎn)下去會依次出現(xiàn) 彈窗 1, 還有右擊的默認(rèn)菜單</p><p>//按鈕1右擊只出現(xiàn) 彈窗 2</p></div> </body> </html>總結(jié)
以上是生活随笔為你收集整理的Vue 阻止事件冒泡的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SiteGround vs WPEngi
- 下一篇: html5倒计时秒杀怎么做,vue 设