Vue.js中v-on指令的用法介紹
v-on指令
v-on指令在Vue.js中用來綁定事件監(jiān)聽器。事件類型由參數指定。表達式可以是一個方法的名字或一個內聯預計,如果沒有修飾符也可以省略。
用在普通元素上時,只能監(jiān)聽原生DOM事件。用在自定義元素組件上時,也可以監(jiān)聽子組件觸發(fā)的自定義事件。
用法:
v-on:事件類型="函數體"
例如:點擊按鈕的時候執(zhí)行play事件
<button v-on:click="play">點擊事件</button>
注意:
在使用v-on指令綁定事件的時候,如果要執(zhí)行的是無參的函數,函數體可以加括號也可以不加括號,下面的兩種寫法是等價的:
<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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue 使用class創(chuàng)建和清除水印的示例代碼
這篇文章主要介紹了vue 使用class創(chuàng)建和清除水印的示例代碼,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12在vue中使用cookie記住用戶上次選擇的實例(本次例子中為下拉框)
這篇文章主要介紹了在vue中使用cookie記住用戶上次選擇的實例(本次例子中為下拉框),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09