事件修饰符
事件名.stop ->阻止冒泡
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Stop Demo with Comparison</title>
<script src="js/vue.js"></script>
<style>
.parent-div {
background-color: lightblue;
padding: 20px;
border: 2px solid skyblue;
}
.child-button {
background-color: lightgreen;
padding: 10px 20px;
border: 1px solid green;
cursor: pointer;
}
.parent-div-without-stop {
background-color: lightcoral;
padding: 20px;
border: 2px solid salmon;
}
.child-button-without-stop {
background-color: lightsalmon;
padding: 10px 20px;
border: 1px solid red;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<h3>使用.stop 修饰符:</h3>
<div class="parent-div" @click="parentClickWithStop">
<p>这是使用.stop 修饰符的父元素区域。</p>
<button class="child-button" @click.stop="childClickWithStop">点击我(子按钮),阻止事件冒泡</button>
</div>
<h3>不使用.stop 修饰符:</h3>
<div class="parent-div-without-stop" @click="parentClickWithoutStop">
<p>这是不使用.stop 修饰符的父元素区域。</p>
<button class="child-button-without-stop" @click="childClickWithoutStop">点击我(子按钮)</button>
</div>
</div>
<script>
new Vue({
el: '#app',
methods: {
parentClickWithStop() {
console.log('使用.stop 修饰符 - Parent div clicked.');
alert('使用.stop 修饰符 - 你点击了父元素!');
},
childClickWithStop() {
console.log('使用.stop 修饰符 - Child button clicked.');
alert('使用.stop 修饰符 - 你点击了子按钮!由于使用了.stop 修饰符,父元素的点击事件不会被触发。只有一个弹窗');
},
parentClickWithoutStop() {
console.log('不使用.stop 修饰符 - Parent div clicked.');
alert('不使用.stop 修饰符 - 你点击了父元素!');
},
childClickWithoutStop() {
console.log('不使用.stop 修饰符 - Child button clicked.');
alert('不使用.stop 修饰符 - 你点击了子按钮!此时父元素的点击事件也会被触发。还有一个弹窗');
}
}
});
</script>
</body>
</html>
事件名.prevent ->阻止默认行为
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Prevent Demo with Comparison</title>
<script src="js/vue.js"></script>
<style>
.link-with-prevent {
color: blue;
text-decoration: underline;
cursor: pointer;
}
.link-without-prevent {
color: purple;
text-decoration: underline;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<h3>使用.prevent 修饰符:</h3>
<a href="https://www.baidu.com" class="link-with-prevent" @click.prevent="preventLinkClick">点击不会跳转到百度的链接</a>
<h3>不使用.prevent 修饰符:</h3>
<a href="https://www.baidu.com" class="link-without-prevent" @click="withoutPreventLinkClick">点击会跳转到百度的链接</a>
</div>
<script>
new Vue({
el: '#app',
methods: {
preventLinkClick() {
console.log('使用.prevent 修饰符,链接点击被阻止,不会跳转到百度。');
alert('使用.prevent 修饰符,链接点击被阻止,不会跳转到百度。');
},
withoutPreventLinkClick() {
console.log('不使用.prevent 修饰符,链接点击会跳转到百度,此消息可能看不到,除非打断跳转。');
alert('不使用.prevent 修饰符,链接点击会跳转到百度,此消息可能看不到,除非打断跳转。');
}
}
});
</script>
</body>
</html>