若我們想要按下鍵盤觸發某事件,通常會用 handler
的寫法
而 Vue 提供了更方便的寫法 event.key = "function"
eg. 輸入文字後按下 Enter
能夠直接送出
<input @keyup.enter="submit" />
相當於
function handler(e) {
if (e.key === 'Enter') submit()
}
可以直接使用按鍵的名字去綁定,但要使用 kebab-case 的方式,如
Enter
-> .enter
PageDown
-> .page-down
-
就像是烤肉串的棍子
<template>
<div class="box">
<input
placeholder="按 Enter 提交 / 按 Escape 清空"
v-model="text"
@keyup.enter="submit"
@keyup.escape="clear"
/>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const text = ref('')
const message = ref('')
function submit() {
message.value = `送出了:${text.value}`
}
function clear() {
text.value = ''
message.value = '已清空'
}
</script>
<style scoped>
.box{
gap:5px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
font-size: x-large;
border: solid;
margin-left: 650px;
margin-top: 5px;
height: 200px;
width:350px;
padding: 35px;
}
</style>
Vue 為一些常用的按鍵提供了別名:
.enter
.tab
.delete
(會偵測「Delete」和「Backspace」兩個鍵).esc
.space
.up
.down
.left
.right
只有在 按著 key 再點擊才會觸發
.ctrl
.alt
.shift
.meta
eg.
<template>
<div class="box">
<button @click.ctrl="doSomething">ctrl + click me</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
function doSomething() {
alert('按著 Ctrl 再點擊才觸發')
}
</script>
<style scoped>
.box{
gap:5px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
font-size: x-large;
border: solid;
margin-left: 650px;
margin-top: 5px;
height: 200px;
width:350px;
padding: 35px;
}
</style>
.exact
修飾符.ctrl
:只要有按 Ctrl
就會觸發事件.ctrl.exact
:必須只按 Ctrl
,不能有其他系統鍵。.exact
:必須沒有按任何系統鍵.left
:用滑鼠左鍵點擊才會觸發.right
:用滑鼠右鍵點擊才會觸發.middle
:用滑鼠中鍵點擊才會觸發ref:
https://ithelp.ithome.com.tw/articles/10207356
https://hackmd.io/@Heidi-Liu/note-common
https://developer.mozilla.org/en-US/docs/Glossary/Kebab_case