在事件处理程序中调用 event.preventDefault() 或 event.stopPropagation() 是非常常见的需求。尽管我们可以在方法中轻松实现这点,但更好的方式是:方法只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
为了解决这个问题,Vue.js 为 v-on 提供了事件修饰符。之前提过,修饰符是由点开头的指令后缀来表示的。
<!-- 阻止单击事件继续传播 --> <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>
例子:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="app">
<h1>事件修饰符</h1>
<button @click.once="add(1)">涨一岁</button> <!--只执行一次-->
<p>my age is {{age}}</p>
<div id="canvas" v-on:mousemove="updateXY"> <!--鼠标移动事件-->
{{x}},{{y}} -
<span v-on:mousemove.stop="">stop moving</span> <!--阻止单击事件继续传播 -->
</div>
<a href="http://www.baidu.com/" v-on:click.prevent="alert()">baidu</a>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
new Vue({
el: '#app',
data: {
age: 30,
x: 0,
y: 0
},
methods: {
add: function (inc) {
this.age += inc;
},
substract: function (dec) {
this.age -= dec;
},
updateXY: function(event){
// console.log(event);
this.x = event.offsetX;
this.y = event.offsetY;
},
stopmoving: function(event) {
event.stopPropaggation();
},
alert: function() {
alert("hello world!");
}
}
});
Vue系列文章目录
- vue系列文章(1):对象绑定,属性绑定
- Vue系列文章(2)事件绑定,鼠标点击事件
- vue系列文章(3):事件修饰符
- Vue系列文章(4)键盘事件及键盘修饰符
- vue系列文章(5)双向数据绑定
- vue系列文章(6)计算属性computed
- vue系列文章(7)动态CSS类型绑定
- vue系列文章(8)条件渲染
- vue系列文章(9)v-for条件循环
- vue系列文章(10)vue实战项目demo
- vue系列文章(11):初始化多个实例对象
- vue系列文章(12)初始组件的应用
- Vue系列文章(13)vue cli脚手架
- vue系列文章(14)vue-cli脚手架,组件嵌套,全局组件注册和局部组件注册
- vue系列文章(15)属性传值props
- vue系列文章(16)传值和传引用的类型和区别
- vue系列文章(17)利用事件传递将子组件值传递给父组件
- vue系列文章(18)vue生命周期
- vue系列文章(19)vue路由配置
- vue系列文章(20) vue网络请求vue-resource
如果上面文章对你有用,打赏下我吧@*@