1. 程式人生 > >Vue.js常用指令:v-on

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>