【Vue】基础系列(六)事件处理-常用事件修饰符
原创
©著作权归作者所有:来自51CTO博客作者wx633288bd5c53e的原创作品,请联系作者获取转载授权,否则将追究法律责任
和阿牛一起冲Vue
文章目录
前言
青春,因为奋斗与奉献更美丽。
一、Vue中的事件修饰符
1.prevent:阻止默认事件(常用);
2.stop:阻止事件冒泡(常用);
3.once:事件只触发一次(常用);
4.capture:使用事件的捕获模式;
5.self:只有event.target是当前操作的元素时才触发事件;
6.passive:事件的默认行为立即执行,无需等待事件回调执行完毕;
![在这里插入图片描述 【Vue】基础系列(六)事件处理-常用事件修饰符_前端](https://s2.51cto.com/images/blog/202209/27133254_63328b067fce564739.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=/resize,m_fixed,w_1184)
二、代码演示常用事件修饰符
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件修饰符</title>
<style>* {
margin-top: 20px;
}
.demo1 {
height: 50px;
background-color: pink;
}
.demo2 {
height: 50px;
background-color: blue;
}
.box1 {
height: 100px;
background-color: purple;
}
.box2 {
height: 20px;
background-color: peru;
}</style>
</head>
<body>
<div id="root">
<h1>{{message.name}}</h1>
<h2><a :href="message.url" @click.prevent="showInfo" target="_blank">{{name}}</a></h2>
<!-- 阻止事件冒泡 -->
<div class="demo1" @click="showInfo">
<button @click.stop="showInfo">点我提示信息</button>
</div>
<!-- 事件只触发一次 -->
<div class="demo2">
<button @click.once="showInfo">点我提示信息</button>
</div>
<!-- 使用事件的捕获模式 -->
<div class="box1" @click.capture="showInfo(1)">
box1
<div class="box2" @click="showInfo(2)">
box2
</div>
</div>
</div>
</body>
<script src='vue.js'></script>
<script>.config.productionTip = false;
new Vue({
el: '#root',
data: {
name: 'jack',
message: {
url: 'javascript:void(0)?spm=1000.2115.3001.5343',
name: '勇敢牛牛'
}
},
methods: {
showInfo(e) {
// e.preventDefault();
// 阻止默认行为,事件修饰符=》6个
// 阻止默认事件
// 或者在click后跟上prevent
// e.stopPropagation();
// alert("你是我的小呀小苹果");
console.log(e);
}
}
});</script>
</html>
三、不常用的三个项
<!-- 只有event.target是当前操作的元素时才触发事件; -->
<div class="demo1" @click.self="showInfo">
<button @click="showInfo">点我提示信息</button>
</div>
<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
<ul @wheel.passive="demo" class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<script type="text/javascript">.config.productionTip = false //阻止 vue 在启动时生成生产提示。
new Vue({
el:'#root',
data:{
name:'尚硅谷'
},
methods:{
showInfo(e){
alert('同学你好!')
// console.log(e.target)
},
showMsg(msg){
console.log(msg)
},
demo(){
for (let i = 0; i < 100000; i++) {
console.log('#')
}
console.log('累坏了')
}
}
})</script>
总结
修饰符可以连续写
例如:
<a href="http://www.atguigu.com" @click.prevent.stop="showInfo">点我提示信息</a>