Vue.js常用指令:v-on

一、v-on指令

v-on指令在Vue.js中用来处理对应的事件。用法:

v-on:事件类型="函数体"

例如:点击按钮的时候执行play事件

<button v-on:click="play">点击事件</button>

注意:

在使用v-on指令绑定事件的时候,如果要执行的是无参的函数,函数体可以加括号也可以不加括号,下面的两种写法是等价的:

<button v-on:click="play()">点击事件</button>

等同于

<button v-on:click="play">点击事件</button>

 但是,如果要传递参数,则必须加括号,例如:

<button v-on:click="play(item)">点击事件</button>

 上面的例子是给play函数传递item参数。

注意:v-on的缩写@

上面的代码等同于下面的代码:

<button @click="play">点击事件</button>

代码示例如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>v-on指令</title> <!--引入vue.js--> <script src="node_modules/vue/dist/vue.js" ></script> <script> window.onload=function(){ // 构建vue实例 new Vue({ el:"#my", data:{ age:30 }, // 方法 methods:{ //无参 play:function(){ this.age=40; }, // 有参 playWithPara:function(para){ this.age=para; } } }) } </script></head><body> <div id="my"> <h1>年龄:{{age}}</h1> <button @click="age = 20">设置年龄为20</button> <button @click="play">设置年龄为40</button> <button @click="playWithPara(50)">根据参数设置年龄</button> </div></body></html>

 

一个按钮也可以同时绑定多个事件,例如:

<button v-on="{mouseover:onOver,mouseout:onOut}">绑定多个事件</button>

 

上面我们通过对象的方式绑定多个事件,对象中的键是事件的名称, 值是methods中的成员属性方法

对应的方法:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>v-on指令</title> <!--引入vue.js--> <script src="node_modules/vue/dist/vue.js" ></script> <script> window.onload=function(){ // 构建vue实例 new Vue({ el:"#my", data:{ age:30 }, // 方法 methods:{ //无参 play:function(){ this.age=40; }, // 有参 playWithPara:function(para){ this.age=para; }, onOver:function(){ var current=document.getElementById("mouse"); current.innerText="鼠标移入"; }, onOut:function(){ var current=document.getElementById("mouse"); current.innerText="鼠标移出"; } } }) } </script></head><body> <div id="my"> <h1>年龄:{{age}}</h1> <h1 id="mouse">当前鼠标动作</h1> <button @click="age = 20">设置年龄为20</button> <button @click="play">设置年龄为40</button> <button @click="playWithPara(50)">根据参数设置年龄</button> <button v-on="{mouseover:onOver,mouseout:onOut}">绑定多个事件</button> </div></body></html>

相关文章