Vue綁定事件v-on(@)與修飾符


Vue使用v-on指令綁定事件,簡寫為@,其用在普通元素上時,只能監聽原生 DOM 事件。用在自定義元素組件上時,也可以監聽子組件觸發的自定義事件。

1.修飾符

  • stop - 調用 event.stopPropagation(),停止冒泡。
  • prevent - 調用 event.preventDefault(),組織瀏覽器默認事件。
  • capture - 添加事件偵聽器時使用 capture 模式。
  • self - 只當事件是從偵聽器綁定的元素本身觸發時才觸發回調。
  • {keyCode | keyAlias} - 只當事件是從特定鍵觸發時才觸發回調。
  • native - 監聽組件根元素的原生事件。
  • once - 只觸發一次回調。
  • left - (2.2.0) 只當點擊鼠標左鍵時觸發。
  • right - (2.2.0) 只當點擊鼠標右鍵時觸發。
  • middle - (2.2.0) 只當點擊鼠標中鍵時觸發。
  • passive - (2.3.0) 以 { passive: true } 模式添加偵聽器

2.示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!-- 方法處理器 -->
<button v-on:click="doThis"></button>

<!-- 動態事件 (2.6.0+) -->
<button v-on:[event]="doThis"></button>

<!-- 內聯語句 -->
<button v-on:click="doThat('hello', $event)"></button>

<!-- 縮寫 -->
<button @click="doThis"></button>

<!-- 動態事件縮寫 (2.6.0+) -->
<button @[event]="doThis"></button>

<!-- 停止冒泡 -->
<button @click.stop="doThis"></button>

<!-- 阻止默認行為 -->
<button @click.prevent="doThis"></button>

<!-- 阻止默認行為,沒有表達式 -->
<form @submit.prevent></form>

<!-- 串聯修飾符 -->
<button @click.stop.prevent="doThis"></button>

<!-- 鍵修飾符,鍵別名 -->
<input @keyup.enter="onEnter">

<!-- 鍵修飾符,鍵代碼 -->
<input @keyup.13="onEnter">

<!-- 點擊回調只會觸發一次 -->
<button v-on:click.once="doThis"></button>

<!-- 對象語法 (2.4.0+) -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

//在子組件上監聽自定義事件 (當子組件觸發“my-event”時將調用事件處理器):
<my-component @my-event="handleThis"></my-component>

<!-- 內聯語句 -->
<my-component @my-event="handleThis(123, $event)"></my-component>

<!-- 組件中的原生事件 -->
<my-component @click.native="onClick"></my-component>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM