1.v-on
作用:如果我们想监听用户的点击, 拖拽, 键盘事件等, 可以使用v-on指令,v-on就是用于绑定事件的,通过 v-on 绑定的事件处理函数,需要在 methods 节点中进行声明。
简写:@
举个栗子
<template>
<div id="app">
<a>{{num}}</a>
<br>
<button v-on:click="add2">+2</button>
<p>---------</p>
<button @click="divide2">/2</button>
<p>---------</p>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
num:1,
}
},
methods:{
add2(){
this.num+=2
},
divide2(){
this.num=this.num/2
}
}
}
</script>
2 event
v-on 指令所绑定的事件处理函数中,可以接收到事件对象 event。
<template>
<div id="app">
<a style="color: blue">{{num}}</a>
<br>
<button v-on:click="add2" style="background-color: red">{{key}}</button>
<p>---------</p>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
num:1,
key:'/2'
}
},
methods:{
add2(event){
if (event.target.style.backgroundColor=='blue')
{
event.target.style.backgroundColor='red'
this.num+=2
this.key='/2'
}
else {
event.target.style.backgroundColor='blue'
this.num=this.num/2
this.key='+2'
}
},
}
}
</script>
3 $event
e v e n t 是 v u e 提 供 的 特 殊 变 量 , 用 来 表 示 原 生 的 事 件 参 数 对 象 e v e n t 。 event 是 vue 提供的特殊变量,用来表示原生的事件参数对象 event。 event是vue提供的特殊变量,用来表示原生的事件参数对象event。event 可以解决事件参数对象 event 被覆盖的问题。
<template>
<div id="app">
<a style="color: blue">{{num}}</a>
<br>
<button v-on:click="add2(2,$event)" style="background-color: red">{{key}}</button>
<p>---------</p>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
num:1,
key:'+2'
}
},
methods:{
add2(n,event){
if (event.target.style.backgroundColor=='blue')
{
event.target.style.backgroundColor='red'
this.num+=n
this.key='/'
}
else {
event.target.style.backgroundColor='blue'
this.num=this.num/n
this.key='+'
}
},
}
}
</script>
4 事件修饰符
v-on:click.prevent 阻止默认行为
v-on:click.stop 阻止事件冒泡
v-on:click.capture 以捕获模式触发当前的事件处理函数
v-on:click.once 绑定的事件只触发1次
v-on:click.self 只有在 event.target 是当前元素自身时触发事件处理函数