v-on:Vue 事件觸發器

v-on 能夠透過 Event(如點擊事件)來觸發某個方法。

v-on 寫法與縮寫

一般寫法(以點擊事件為例)

1
<button v-on:click="帶入方法(或其參數) or 直接撰寫">按鈕</button>

縮寫(以點擊事件為例)

1
<button @click="帶入方法(或其參數) or 直接撰寫">按鈕</button>

事件修飾符:prevent

  • HTML 中的 a 或是 form 表單內的 post 會分別在點擊鏈結跟 submit 後跳轉鏈結
  • 若無須跳轉鏈結,可在 v-on 後加入 .prevent,可移除其事件
  • 當然也可以增加事件,可參考官方文件:https://cn.vuejs.org/v2/api/#v-on

a 鏈結範例

1
<a href="https://www.google.com" @click.prevent="方法變數">鏈結</a>
  • 加入 .prevent 前,執行完方法後就會跳轉鏈結
  • 加入 .prevent 後,執行完方法不會跳轉鏈結

表單 submit 範例

1
2
3
4
<form action="https://www.google.com/" @submit.prevent="方法變數">
<input type="text">
<input type="submit">
</form>
  • 加入 .prevent 前,點擊 submit 會執行完方法後並跳轉鏈結
  • 加入 .prevent 後,點擊 submit 執行完方法但不會跳轉鏈結

範例程式碼

HTML

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
<div id="app">
<button @click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
<hr>
<button @click="say('hi')">say hi</button>
<button @click="say('what')">say what</button>
<hr>
<a href="https://www.google.com/" @click.prevent="clickfu">有 prevent 的狀況下</a><br>
<a href="https://www.google.com/" @click="clickfu">沒有 prevent 的狀況下</a>
<hr>
<form action="https://www.google.com/" @submit.prevent="submitFu">
<h3>有 prevent</h3>
<input type="text">
<input type="submit">
</form>
<form action="https://www.google.com/" @submit="submitFu">
<h3>沒有 prevent</h3>
<input type="text">
<input type="submit">
</form>
<hr>
<p>
<label for="enter">針對 input 按下 Enter 會觸發按鍵精靈</label>
<input id="enter" type="text" @keyup.enter="onEnter">
</p>
<p>
<label for="a">針對 input 按下 Enter 會觸發按鍵精靈</label>
<input id="a" type="text" @keyup.a="onEnter">
</p>
<p>
<label for="b">針對 input 按下 Enter 會觸發按鍵精靈</label>
<input id="b" type="text" @keyup.b="onEnter">
</p>
<p>
<label for="c">針對 input 按下 Enter 會觸發按鍵精靈</label>
<input id="c" type="text" @keyup.c="onEnter">
</p>
</div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const app = {
data () {
return {
counter: 0,
}
},
methods: {
say (message) {
alert(message);
},
clickfu () {
alert('prevent');
},
submitFu () {
alert('表單傳遞');
},
onEnter () {
alert('按鍵精靈');
},
},
}

Vue.createApp(app).mount('#app');