事件处理程序
v-on
是Vue用来监听DOM事件的指令缩写是@
<ul id="app4">
<button @click="couter()">click</button>
<li>按钮点击了{{num}}次</li>
<button @click="hello">Click me</button>
</ul>
//JS代码
var example=new Vue({
el:"#app4",
data:{
num:0
},
methods:{
couter:function(){
this.num=this.num+1;
},
hello:function(){
alert("hello "+this.num);
}
}
})
使用起来有点像在标签中插入onclick
<div id="app5">
<button @click="alert('hello')">click</button>
//之后绑定Vue就可以使用
</div>
当然有事件的地方就肯定有event.preventDefault()
和event.stopPropagation()
方法
在Vue中我们只需要在后面用.stop
和.prevent
等等可以达到效果
//阻止事件冒泡
<a v-on:click.stop="hello"></a>
//阻止默认事件
<form v-on:submit.prevent="onSubmit"></form>
//添加事件处理程序使用捕获模式
<div v-on:click.capture="doThis">...</div>
//只当在 event.target 是当前元素自身时触发处理函数
<div v-on:click.self="doThat">...</div>
//只触发一次
<div @click.once="OneTime"></div>