版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://sunkuan.blog.csdn.net/article/details/110423072
通过上一篇我们大致体验了 Vue 事件,本篇将继续深入讲解 Vue 事件 的 事件修饰符,这个 事件修饰符 就是用来装饰 Vue 事件 的,它和事件连用,决定着事件触发条件或者是阻止事件的触发机制。当然多个 事件修饰符 也可以连用。
本篇博客会给大家介绍四个常用的 事件修饰符:
.stop
、.prevent
、.self
、.once
。
一、stop事件修饰符(阻止冒泡)
stop事件修饰符 用来阻止事件冒泡,事件冒泡是指父元素绑定了事件,当触发其子元素的事件时,默认也会触发父元素的事件。
<body>
<div id="app">
<div class="father" style="width:100px;height:100px;background:red" @click="father">
<!-- 用来阻止事件冒泡 -->
<div class="son" style="width:50px;height:50px;background:blue" @click.stop="son"></div>
</div>
</div>
<!-- 引入 vue 的 js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el : '#app',
data : {
},
methods : {
father() {
alert('father');
},
son() {
alert('son');
}
}
});
</script>
</body>
二、prevent事件修饰符(阻止标签默认行为)
prevent事件修饰符 用来阻止标签的默认行为,比如 a 标签的默认行为是跳转页面,使用了 prevent事件修饰符 后可以阻止跳转。
<body>
<div id="app">
<div class="father" style="width:100px;height:100px;background:red;" @click="father">
<a href="http://www.baidu.com" @click.prevent.stop="aClick">百度一下1</a><br>
<a href="http://www.baidu.com" @click.prevent="aClick">百度一下2</a>
</div>
</div>
<!-- 引入 vue 的 js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el : '#app',
data : {
},
methods : {
aClick() {
alert('a被点击了!');
},
father() {
alert('father被点击了!');
}
}
});
</script>
</body>
三、self事件修饰符(只关心标签本身的事件,不监听事件冒泡)
self事件修饰符 用来针对当前标签触发的事件,只关心自己标签上触发的事件,不监听事件冒泡。
<body>
<div id="app">
<!-- 只能触发发生在自身的事件 -->
<div class="father" style="width:100px;height:100px;background:red" @click.self="father">
<!-- 用来阻止事件冒泡 -->
<div class="son" style="width:50px;height:50px;background:blue" @click="son"></div>
<div class="son" style="width:50px;height:50px;background:yellow" @click="son"></div>
</div>
</div>
<!-- 引入 vue 的 js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el : '#app',
data : {
},
methods : {
father() {
alert('father');
},
son() {
alert('son');
}
}
});
</script>
</body>
四、once事件修饰符(只触发一次)
once事件修饰符 用来让指定事件只触发一次。
<body>
<div id="app">
<div class="father" style="width:100px;height:100px;background:red" @click="father">
<!-- 只执行一次点击事件 -->
<div class="son" style="width:50px;height:50px;background:blue" @click.once="son"></div>
<!-- 只阻止一次事件冒泡 -->
<div class="son" style="width:50px;height:50px;background:yellow" @click.stop.once="son"></div>
</div>
</div>
<!-- 引入 vue 的 js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const vm = new Vue({
el : '#app',
data : {
},
methods : {
father() {
alert('father');
},
son() {
alert('son');
}
}
});
</script>
</body>