溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue.JS事件處理的案例

發(fā)布時間:2020-12-02 11:11:21 來源:億速云 閱讀:163 作者:小新 欄目:web開發(fā)

這篇文章主要介紹Vue.JS事件處理的案例,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

Vuejs向我們提供了一個名為v:on的指令,它可以幫助我們注冊和偵聽dom事件,這樣無論何時觸發(fā)事件,都會調(diào)用傳遞給該事件的方法。

v:on指令的語法

<!-- v:on:eventname="methodname" -->

<button v:on:click="handleClick">Click</button>

在上面的代碼中,我們監(jiān)聽按鈕上的click事件,以便每當用戶單擊按鈕時,它都會調(diào)用handleClick方法。

<template>
   <div>
      <h2>{{num}}</h2>
      <button  v-on:click="increment">Increment</button>
   </div>
</template>

<script>
   export default{
       data:function(){
           return{
               num:0
           }
       },
       methods:{
           increment:function(){
               this.num=this.num+1
           }
       }
   }
</script>

如何將參數(shù)傳遞給事件處理程序?

有時事件處理程序方法也可以接受參數(shù)。

<template>
   <div>
       <h2>{{num}}</h2>
       <!-- 參數(shù)10被傳遞給increment方法-->
      <button  v-on:click="increment(10)">Increment By 10</button>
   </div>
</template>

<script>
   export default{
       data:function(){
           return{
               num:0
           }
       },
       methods:{
           //參數(shù)`value`
           increment:function(value){
               this.num =this.num+value
           }
       }
   }
</script>

這里,我們創(chuàng)建了一個只有一個參數(shù)值的increment方法,以便將參數(shù)傳遞給increment(10)方法。

如何訪問默認事件對象?

要訪問方法vuejs中的默認事件對象,需要提供一個名為$event的變量。

<template>
   <!-- 我們正在傳遞一個$event變量 -->
  <input placeholder="name" v-on:onchange="handleChange($event)" />
</template>

<script>
 export default{
     methods:{
         handleChange:function($event){
             console.log($event.target.value)
         }
     }
 }
</script>

在這里,我們通過使用Vuejs提供的特殊$event變量來訪問事件對象。

有時我們需要同時訪問事件對象和參數(shù)。

<template>
   <!-- 我們傳遞參數(shù)加上$event變量  -->
  <button v-on:click="hitMe('You hitted me',$event)">
    Hit me Hard
  </button>
</template>

<script>
 export default{
     methods:{
         handleChange:function(message,$event){
             $event.preventDefault()
             console.log(message)
         }
     }
 }
</script>

簡寫語法

vuejs還提供了一種簡寫語法來偵聽dom事件。

 <!--簡寫語法@eventname="method"-->
<button @click="handleClick"></button>

  <!-- 長語法 -->
<button v-on:click="handleClick"></button>

以上是“Vue.JS事件處理的案例”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI