
vue3中的事件修饰符有:
.stop // 阻止事件传递 .prevent // 停止默认事件 .self // 自身执行 .capture // 使用捕获模式 .once // 只执行一次 .passive // 立即执行
作用:阻止冒泡事件
冒泡事件:子元素的事件传递到父元素,即你促发子元素的click事件,由于冒泡,会使外层的父元素的click事件同时触发。
<div @click="shout(1)"> <button @click="shout(2)">点击查看内容</button> </div>
内容弹出时先触发弹出2,再触发弹出1。
方法一:在子元素的click后面直接加上.stop,就可以阻止冒泡事件了:
<div @click="shout(1)"> <button @click.stop="shout(2)">点击查看内容</button> </div>
方法二:使用参数对象的stopDefault方法,如下:
<div @click="shout(1)"> <button @click="shout(2)">点击查看内容</button> </div> methods: { shout(e){ e.stopDefault() } }
作用:阻止浏览器的默认事件
默认事件:移动端浏览器的下拉刷新事件、点击超链接会跳转页面.......
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="showInfo">点我提示信息</a>
如上面的示例,点击a标签就会跳转到新链接,这个时候我们需要阻止默认事件,除了去掉href链接这个方法外,还可以用prevent阻止默认事件。
方法一:在click后面直接加上.prevent,如下:
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click.prevent="showInfo">点我提示信息</a>
方法二:使用参数对象的preventDefault方法,如下:
<a href="http://www.baidu.com" rel="external nofollow" rel="external nofollow" rel="external nofollow" @click="showInfo($event)">点我提示信息</a> methods: { showInfo(e){ e.preventDefault() } }
作用:阻止自身事件促发,但不会阻止冒泡
<div class="outer" @click="outer"> <div class="middle" @click.self="middle"> <button @click="inner">点击</button> </div> </div>
当我们点击button的时候,先执行inner,传递到middle,此时middle里有一个.self,.self阻止了middle的click事件,所以继续冒泡到outer,执行outer的click事件。
结果:执行click事件的顺序:inner ----> outer
作用:打乱冒泡顺序(即可以理解为给元素添加一个监听器,当元素发生冒泡时,先触发带有该修饰符的元素。若有多个该修饰符,则由外而内触发。)
<!-- captrue:使用事件的捕捉模式 --> <div class="box1" @click.capture="showMsg(1)"> div1 <div class="box2" @click="showMsg(2)"> div2 </div> </div> 上面的执行顺序是1、2
作用:事件只触发一次(常用)
作用:事件的默认行为立即执行,无需等待事件回调执行完毕(不常用)
不要把 .passive 和 .prevent 一起使用,因为 .prevent 将会被忽略。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。