Vue常见面试题,事件修饰符
① once 设置事件只能触发一次(第二次以及以上将不会触发):
<button @click="btn">测试按钮</button>
btn(){
console.log("开始测试");
}
② prevent 阻止默认事件的发生(例如,点击超链接,不会进行跳转)
<a href="www.baidu.com" @click.prevent>百度</a>
③ stop 阻止冒泡(阻止事件向上级DOM元素传递)
<div style="width: 150px;height: 150px;background-color: red" @click="btn1">
<div style="width: 100px;height: 100px;background-color: #1A89D9" @click="btn2">
<div style="width: 50px;height: 50px;background-color: #b3e19d" @click="btn3">
</div>
</div>
</div>
btn1(){
console.log("btn1按钮");
},
btn2(){
console.log("btn2按钮");
},
btn3(){
console.log("btn3按钮");
},
点击最里层DIV时:
更新代码(加入stop,再次点击最里层DIV时):
<div style="width: 150px;height: 150px;background-color: red" @click="btn1">
<div style="width: 100px;height: 100px;background-color: #1A89D9" @click="btn2">
<div style="width: 50px;height: 50px;background-color: #b3e19d" @click.stop="btn3">
</div>
</div>
</div>
④ self 避免冒泡事件的影响(将事件绑定到自身,只有自身才能触发)
<div style="width: 150px;height: 150px;background-color: red" @click="btn1">
<div style="width: 100px;height: 100px;background-color: #1A89D9" @click.self="btn2">
<div style="width: 50px;height: 50px;background-color: #b3e19d" @click="btn3">
</div>
</div>
</div>
⑤ ctrl 当按住ctrl键时,点击才有效
<button @click.ctrl="btn">测试按钮</button>
⑥ capture 捕获冒泡(即有冒泡发生时,有该修饰符的DOM元素会先执行,然后再按自然顺序执行触发的事件)
<div style="width: 150px;height: 150px;background-color: red" @click.capture="btn1">
<div style="width: 100px;height: 100px;background-color: #1A89D9" @click="btn2">
<div style="width: 50px;height: 50px;background-color: #b3e19d" @click="btn3">
</div>
</div>
</div>
点击最里层DIV时:
总结
每天一个提升小技巧!!!