<template> <div > <div @click="show1($event)"> <div @click="show2($event)">点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show1: function (ev) { alert(1) }, show2: function (ev1) { alert(2) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
那么但阻止冒泡后就只会弹一次
eg:原生js阻止冒泡
ev1.cancelBubble=true
<template> <div > <div @click="show1($event)"> <div @click="show2($event)">点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show1: function (ev) { alert(1) }, show2: function (ev1) { ev1.cancelBubble=true alert(2) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
那么vue自己封装的阻止冒泡方法呢?
@click.stop="show2()"
eg:
<template> <div > <div @click="show1()"> <div @click.stop="show2()">点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show1: function () { alert(1) }, show2: function (ev1) { alert(2) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
7.阻止默认行为:比如:如下右键之后会将默认的菜单带出来
<template> <div > <div> <div @contextmenu="show2()">右键点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show2: function (ev1) { alert(2) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
效果:
那么就有了阻止默认行为
ev1.preventDefault();
eg:
<template> <div > <div> <div @contextmenu="show2($event)">右键点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show2: function (ev1) { alert(2); ev1.preventDefault(); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
点击后默认菜单将不会显示(PS早360浏览器右键无效)
vue里面的封装的阻止默认行为的方法:
@contextmenu.prevent="show2()"
eg:
<template> <div > <div> <div @contextmenu.prevent="show2()">右键点击我呀</div> </div> </div> </template> <script> export default { name: 'HelloWorld', data () { return { hide : true } }, methods:{ show2: function (ev1) { alert(2); } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
8.其他事件修饰符用法都一样就不再赘述
.capture
.self
.once
<!-- 阻止单击事件继续传播 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 --> <form v-on:submit.prevent="onSubmit"></form> <!-- 修饰符可以串联 --> <a v-on:click.stop.prevent="doThat"></a> <!-- 只有修饰符 --> <form v-on:submit.prevent></form> <!-- 添加事件监听器时使用事件捕获模式 --> <!-- 即元素自身触发的事件先在此处处理,然后才交由内部元素进行处理 --> <div v-on:click.capture="doThis">...</div> <!-- 只当在 event.target 是当前元素自身时触发处理函数 --> <!-- 即事件不是从内部元素触发的 --> <div v-on:click.self="doThat">...</div>