當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js v-on用法及代碼示例

將事件偵聽器附加到元素。

速記: @

期望: Function | Inline Statement | Object (without argument)

參數: event(如果使用 Object 語法,則可選)

修飾符:

  • .stop - 調用 event.stopPropagation()
  • .prevent - 調用 event.preventDefault()
  • .capture - 在捕獲模式下添加事件監聽器。
  • .self - 僅在從該元素調度事件時觸發處理程序。
  • .{keyAlias} - 僅在某些鍵上觸發處理程序。
  • .once - 最多觸發一次處理程序。
  • .left - 僅觸發鼠標左鍵事件的處理程序。
  • .right - 僅觸發鼠標右鍵事件的處理程序。
  • .middle - 僅觸發中鍵鼠標事件的處理程序。
  • .passive - 使用 { passive: true } 附加一個 DOM 事件。

細節

事件類型由參數表示。表達式可以是方法名稱、內聯語句,如果存在修飾符,則可以省略。

在普通元素上使用時,它會監聽原生 DOM 事件隻要。在自定義元素組件上使用時,它會監聽自定義事件在該子組件上發出。

當監聽原生 DOM 事件時,該方法接收原生事件作為唯一參數。如果使用內聯語句,該語句可以訪問特殊的 $event 屬性:v-on:click="handle('ok', $event)"

v-on 還支持綁定到不帶參數的事件/偵聽器對的對象。請注意,使用對象語法時,它不支持任何修飾符。

例子:

<!-- method handler -->
<button v-on:click="doThis"></button>

<!-- dynamic event -->
<button v-on:[event]="doThis"></button>

<!-- inline statement -->
<button v-on:click="doThat('hello', $event)"></button>

<!-- shorthand -->
<button @click="doThis"></button>

<!-- shorthand dynamic event -->
<button @[event]="doThis"></button>

<!-- stop propagation -->
<button @click.stop="doThis"></button>

<!-- prevent default -->
<button @click.prevent="doThis"></button>

<!-- prevent default without expression -->
<form @submit.prevent></form>

<!-- chain modifiers -->
<button @click.stop.prevent="doThis"></button>

<!-- key modifier using keyAlias -->
<input @keyup.enter="onEnter" />

<!-- the click event will be triggered at most once -->
<button v-on:click.once="doThis"></button>

<!-- object syntax -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

監聽子組件上的自定義事件(在子組件上發出 "my-event" 時調用處理程序):

<MyComponent @my-event="handleThis" />

<!-- inline statement -->
<MyComponent @my-event="handleThis(123, $event)" />

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 v-on。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。