Event modifier Vue事件修饰符
在事件处理程序中调用event.preventDefault() 或 event.stopPropagation() 是非常常见的需求。
尽管我们可以在方法中轻松实现这点,但更好的方式是:
方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
为了解决这个问题,Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。
.stop:阻止单击事件继续传播
- 在html:
.prevent:提交事件不再重载页面
- 在html:
<div id="app" style="position:absolute;top: 100px;left: 100px;"> <form v-on:submit.prevent="onSubmit"> <input type="text"> <input type="submit"> </form> </div>
- 在js:
new Vue({
el:"#app"
})
提交表单后页面不会重载
.once:事件只能点击一次
<div id="app" style="position:absolute;top: 100px;left: 100px;">
<button type="button" class="btn btn-info" @click.once = "add">加1岁</button>
<h2>{{age}}</h2>
</div>
<script>
new Vue({
el:"#app",
data:{
age:18
},
methods:{
add:function(){
this.age++;
}
}
})
</script>
.capture事件修饰符的作用添加事件侦听器时使用事件捕获模式
- html
<div id="app"> <div class="parent" @click.capture="parent">parent <div class="child" @click="child">child <div class="grandson" @click="grandson">grandson</div> </div> </div> </div>
- css
.parent{ width: 200px; height: 200px; background-color: red; } .child{ width: 100px; height: 100px; background-color: yellow; } .grandson{ width: 50px; height: 50px; background-color: green; }
- js
new Vue({ el:"#app", methods:{ parent:function(){ console.log("parent") }, child:function(){ console.log("child") }, grandson:function(){ console.log("grandson") } } })
点击grandson的时候,弹出的顺序为:parent、grandson、child;
由于parent有修饰符,故而先触发事件,然后就是grandson本身触发,最后冒泡事件。
以此类推:点击child的时候,触发顺序是parent,child,parent有修饰符,先触发。
.self 只点自己身上才运行
<div id="app">
<div class="parent" @click="parent">parent
<div class="child" @click.self="child">child
<div class="grandson" @click="grandson">grandson</div>
</div>
</div>
</div>
点grandson的时候,不能冒泡到child,因为child中有.self的事件修饰符,只有点child的时候,才能打印child