Vue中的事件修饰符:
- prevent:阻止默认事件
- stop:阻止事件冒泡
- once:事件只触发一次
- capture:使用事件捕获模式
- self:只有event.target是当前元素时触发
- passive:事件的默认行为立即执行,不需要等待回调函数执行完成
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>modifier</title> <script type="text/javascript" src="../js/vue.js"></script> <style type="text/css"> * { margin: 10px; } </style> </head> <body> <div class="root"> <span>prevent修饰符:</span> <div style="background-color: skyblue"> <h1>姓名:{{name}}</h1> <a href="https:www.baidu.com" @click="showMsg">不使用prevent修饰符,页面跳转至百度</a><br> <!--使用 prevent 修饰符,相当于原生js中的event.preventDefault();--> <a href="https:www.baidu.com" @click.prevent="showMsg">使用prevent修饰符,页面不跳转</a> </div> <span>stop修饰符:</span> <div @click="showMsg2" style="background-color: skyblue"> 最外层 <div @click.stop="showMsg2" style="background-color: yellow"> 中间层 <!--使用 stop 修饰符,相当于相当于原生js中的event.stopPropagation();--> <button @click.stop="showMsg2">内层按钮</button> </div> </div> <span>once 修饰符:</span> <div style="background-color: yellowgreen"> <button @click.once="showMsg3">点击弹窗</button> </div> <span>capture 修饰符:</span> <span>不加 capture</span> <div @click="showMsg4('外层div')" style="background-color: skyblue"> 最外层 <div @click="showMsg4('内层div')" style="background-color: yellow"> 中间层 <button @click="showMsg4('按钮')">内层按钮</button> </div> </div> <span>中间层div添加capture</span> <div @click="showMsg4('最外层div')" style="background-color: skyblue"> 最外层 <div @click.capture="showMsg4('中间层div')" style="background-color: yellow"> 中间层 <button @click="showMsg4('按钮')">内层按钮</button> </div> </div> <span>self 修饰符:</span> <span>中间层div添加self,点击按钮时,不触发中间层div的点击事件</span> <div @click="showMsg5($event,'最外层div')" style="background-color: skyblue"> 最外层 <div @click.self="showMsg5($event,'中间层div')" style="background-color: yellow"> 中间层 <button @click="showMsg5($event,'按钮')">内层按钮</button> </div> </div> </div> <script type="text/javascript"> Vue.config.productionTip = false;//关闭生产提示 let person = { name: "张三", age: 18, }; const vm = new Vue({ el: ".root", data: person, methods: { showMsg(event) { // event.preventDefault(); alert("你好," + this.name); }, showMsg2(event) { // event.stopPropagation(); alert("默认会弹多次,使用stop只弹一次"); }, showMsg3() { alert("默认点击就弹窗,使用once只在第一次点击弹窗"); }, showMsg4(sign) { alert(sign + "绑定的事件触发"); }, showMsg5(event,sign) { alert(event.target); alert(sign + "绑定的事件触发"); } } }); </script> </body> </html>