將事件偵聽器附加到元素。
速記:
@
期望:
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)" />
相關用法
- Vue.js v-pre用法及代碼示例
- Vue.js v-html用法及代碼示例
- Vue.js v-bind用法及代碼示例
- Vue.js v-slot用法及代碼示例
- Vue.js v-else用法及代碼示例
- Vue.js v-cloak用法及代碼示例
- Vue.js v-else-if用法及代碼示例
- Vue.js v-text用法及代碼示例
- Vue.js useSSRContext()用法及代碼示例
- Vue.js app.directive()用法及代碼示例
- Vue.js mergeProps()用法及代碼示例
- Vue.js app.config.warnHandler用法及代碼示例
- Vue.js pipeToWebWritable()用法及代碼示例
- Vue.js app.use()用法及代碼示例
- Vue.js h()用法及代碼示例
- Vue.js serverPrefetch用法及代碼示例
- Vue.js customRef()用法及代碼示例
- Vue.js <Transition>用法及代碼示例
- Vue.js inject()用法及代碼示例
- Vue.js mixins用法及代碼示例
- Vue.js ComponentCustomProps用法及代碼示例
- Vue.js reactive()用法及代碼示例
- Vue.js ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 v-on。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。