事件修饰符
在事件处理程序中调用 event.preventDefault() 或 event.stopPropagation() 是非常常见的需求。尽管我们可以在方法中轻松实现这点,但更好的方式是:方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
注:event.preventDefault() 是阻止默认事件发生,比如点击提交按钮,提交表单的时候,如果你不想点击的时候提交,就可以调用该方法,event.stopPropagation()是阻止事件冒泡到父节点中去,一下是jQuery的实现,我们可以看到通过event.stopPropagation实现了需求,但是我们希望事件只是对数据的处理,而非掺杂着对DOM的操作
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>事件修饰符</title>
<script type="text/javascript" src="../vue.js"></script>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("span").click(function(event) {
//阻止父元素冒泡
event.stopPropagation();
alert("The span element was clicked.");
});
$("p").click(function(event) {
alert("The p element was clicked.");
});
$("div").click(function() {
alert("The div element was clicked.");
});
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
This is a div element.
<p style="background-color:pink">This is a p element, in the div element. <br><span style="background-color:orange">This is a span element in the p and the div element.</span></p>
</div>
</body>
</html>
所以,Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。
.stop
.prevent
.capture
.self
.once
.passive
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即元素自身触发的事件先在此处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>
使用修饰符时,顺序很重要;相应的代码会以同样的顺序产生。因此,用 v-on:click.prevent.self 会阻止所有的点击,而 v-on:click.self.prevent 只会阻止对元素自身的点击。
我们下面修改一下jQuery的代码(未阻止事件冒泡):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>事件修饰符</title>
<script type="text/javascript" src="../vue.js"></script>
</head>
<body>
<div id="app12" v-on:click="divMethod" style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
This is a div element.
<p v-on:click="pMethod" style="background-color:pink">This is a p element, in the div element. <br><span v-on:click="spanMethod" style="background-color:orange">This is a span element in the p and the div element.</span></p>
</div>
<script>
var vm=new Vue({
el:"#app12",
data:{
},
methods:{
divMethod:function(){
alert("The div element was clicked.");
},
pMethod:function(){
alert("The p element was clicked.");
},
spanMethod:function(){
alert("The span element was clicked.");
}
}
})
</script>
</body>
</html>
下面是设置阻止冒泡,
只需将span标签修改为:
<span v-on:click.stop="spanMethod" style="background-color:orange">
也就是在click上加.stop修饰符,就会阻止事件冒泡;