Vue3 - 事件處理
tags: Vue
category: Front-End
description: Vue3 - 事件處理
created_at: 2022/07/16 14:30:00
回到 手把手開始寫 Vue3
前言
終於到事件處理了,不然前面都盡量使用 setTimeout
來展示東西改變。
之後可以放心做些按鈕出來玩了
基本使用
使用了框架之後,處理事件不用再像以往要寫長長的 addEventListener
(什麼你說反正都有intellisense
? 總之就是很煩很亂)
先來看個範例,假設我要點擊(click
)事件,按鈕被按下之後 count
要被增加
方法1: 寫在行內,就很像很古早的 onClick
<script setup>
import { ref } from "vue";
const count = ref(0);
</script>
<template>
<div>{{ count }}</div>
<button class="bg-blue-500 text-white px-4 py-2" v-on:click="count++">
Count++
</button>
</template>
當按鈕被點下,count
的值就會被 +1
方法2: 抽出一個函數去處理
<script setup>
import { ref } from "vue";
const count = ref(0);
const add = () => {
count.value++;
};
</script>
<template>
<div>{{ count }}</div>
<button class="bg-blue-500 text-white px-4 py-2" v-on:click="add">
Count++
</button>
</template>
跟上面的效果是一樣的。
再來是因為這個功能跟屬性綁定一樣都很常用,所以也有簡寫的方式,是使用 @
符號做開頭,像是這樣
<button class="bg-blue-500 text-white px-4 py-2" @click="add">Count++</button>
事件變數呢?
自己加,像這樣
const add = (e) => {
console.log(e);
count.value++;
};
看你喜歡叫什麼,event
?,$event
?,或是簡短的 e
都可以。
會看到像這樣的東西
PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
傳入參數
直接寫在呼叫的地方就可以了。
<script setup>
const say = (text) => {
alert(text);
};
</script>
<template>
<div>{{ count }}</div>
<button class="bg-blue-500 text-white px-4 py-2" @click="say('hello')">
SayHello
</button>
<button class="bg-blue-500 text-white px-4 py-2" @click="say('hi')">
SayHi
</button>
</template>
那我的事件變數呢?
有兩個方式
假設我先修改 say
的定義
const say = (e, text) => {
console.log(e, text);
};
方法1: 使用 $event
保留字傳入
<button
class="bg-blue-500 text-white px-4 py-2"
@click="say($event, 'hello')"
>
SayHello
</button>
上面那個 $event
就是他的事件變數
方法2: 使用行內函數得到事件變數再傳入
<button
class="bg-blue-500 text-white px-4 py-2"
@click="(e) => say(e, 'hello')"
>
SayHello
</button>
那個 e
就是事件變數
修飾符
平常有在寫 javascript
的人應該知道有時候監聽事件都要加上像是 preventDefault()
或是 stopPropagation()
之類的,而修飾符就是幫你處理這些事。
只要在監聽事件後面加上一個 .
,放入後綴就可以了
像是下面這些:
- .stop
- .prevent
- .self
- .capture
- .once
- .passive
直接貼官方文件來加說明
<!-- 事件將不會再往上傳 -->
<a @click.stop="doThis"></a>
<!-- 送出表單將不刷新頁面 -->
<form @submit.prevent="onSubmit"></form>
<!-- 修飾符可以接著使用 -->
<a @click.stop.prevent="doThat"></a>
<!-- 只是修飾符 -->
<form @submit.prevent></form>
<!-- 只觸發在自己,也就是 event.target 等於 element -->
<div @click.self="doThat">...</div>
然後這些修飾符如果接著使用,會有順序的問題,例如
@click.prevent.self
: 會阻止點擊元素自己跟子元素的默認操作@click.self.prevent
: 只會阻止點擊元素自己的默認操作。
其他細節可以再參考官方文件,像是還有跟鍵盤、滑鼠相關的修飾符,搭配著範例應該不難看懂。
最後更新時間: 2022年07月16日.