vue阻止事件
1.事情对象
<!DOCTYPEhtml><html><head><title></title><metacharset="utf-8"><scriptsrc="http://unpkg.com/vue/dist/vue.js"></script><scripttype="text/javascript">window.onload=function(){varvm=newVue({el:'#box',methods:{show:function(event){console.log(event);//event这个就是事件对象了}}});}</script></head><body><divid="box"><inputtype="button"value="按钮"@click="show($event)"></div></body></html>
通过show($event)把事件对象传到方法里
2.事件冒泡
<!DOCTYPEhtml><html><head><title></title><metacharset="utf-8"><scriptsrc="http://unpkg.com/vue/dist/vue.js"></script><scripttype="text/javascript">window.onload=function(){varvm=newVue({el:'#box',methods:{show:function(){alert(1);},show1:function(){alert(2);}}});}</script></head><body><divid="box"><div@click="show1()"><inputtype="button"value="按钮"@click="show()"></div></div></body></html>
点击按钮的话他会,执行show ,show1方法,依次弹出1,2。
怎么来阻止
<1>利用我们上面讲过的event
对象: event.cancelBubble =true; //这种就阻止了
<!DOCTYPEhtml><html><head><title></title><metacharset="utf-8"><scriptsrc="http://unpkg.com/vue/dist/vue.js"></script><scripttype="text/javascript">window.onload=function(){varvm=newVue({el:'#box',methods:{show:function(event){alert(1);event.cancelBubble=true;},show1:function(){alert(2);}}});}</script></head><body><divid="box"><div@click="show1()"><inputtype="button"value="按钮"@click="show($event)"></div></div></body></html>
<2>利用vue的方法阻止冒泡:给HTML元素绑定click事件的时候,改为@click.stop="show()"
<!DOCTYPEhtml><html><head><title></title><metacharset="utf-8"><scriptsrc="http://unpkg.com/vue/dist/vue.js"></script><scripttype="text/javascript">window.onload=function(){varvm=newVue({el:'#box',methods:{show:function(event){alert(1);//event.cancelBubble=true;},show1:function(){alert(2);}}});}</script></head><body><divid="box"><div@click="show1()"><inputtype="button"value="按钮"@click.stop="show()"></div></div></body></html>
3.默认行为
比如contextmenu右键菜单
<!DOCTYPEhtml><html><head><title></title><metacharset="utf-8"><!--//<scriptsrc="vue.js"></script>--><scriptsrc="http://unpkg.com/vue/dist/vue.js"></script><scripttype="text/javascript">window.onload=function(){varvm=newVue({el:'#box',methods:{show:function(){alert(1);},show1:function(){alert(2);}}});}</script></head><body><divid="box"><inputtype="button"value="按钮"@contextmenu="show()"><inputtype="button"value="按钮1"@contextmenu.prevent="show1()"><p>//按钮右击点下去会依次出现弹窗1,还有右击的默认菜单</p><p>//按钮1右击只出现弹窗2</p></div></body></html>
@click.stop.prevent,相当于同时执行:
event.stopPropagation();
event.preventDefault();
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。