Vue 事件处理
我们可以使用 v-on 指令(通常简写为 @ 符号)来监听 DOM 事件,并在触发时运行一些 JavaScript 代码。这使得我们可以创建交互式的用户界面。
监听事件
用法为 v-on:click="methodName" 或使用快捷方式 @click="methodName"。
vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<!-- 当按钮被点击时,会调用 increment 方法 -->
<button @click="increment">Count is: {{ count }}</button>
</template>内联事件处理器
除了直接绑定到一个方法,你也可以在内联处理器中执行简单的语句:
vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<!-- 在事件处理器中直接编写 JavaScript -->
<button @click="count++">Add 1</button>
<p>The count is: {{ count }}</p>
</template>在方法中传递参数
在处理事件时,通常需要向方法传递参数。
vue
<script setup>
function greet(name) {
alert(`Hello, ${name}!`)
}
</script>
<template>
<button @click="greet('Vue')">Greet</button>
</template>访问事件参数
有时,我们需要访问原始的 DOM 事件对象。你可以使用特殊的 $event 变量将它传入方法:
vue
<script setup>
function warn(message, event) {
// event 是原生的 DOM 事件
if (event) {
event.preventDefault()
}
alert(message)
}
</script>
<template>
<button @click="warn('Form cannot be submitted yet.', $event)">Submit</button>
</template>事件修饰符 (Event Modifiers)
在处理事件时,我们经常需要调用 event.preventDefault() 或 event.stopPropagation()。为了解决这个问题,Vue 为 v-on 提供了事件修饰符。修饰符是以点开头的指令后缀。
.stop: 调用event.stopPropagation()。.prevent: 调用event.preventDefault()。.capture: 添加事件侦听器时使用 capture 模式。.self: 只当事件是从侦听器绑定的元素本身触发时才触发回调。.once: 点击事件将只会触发一次。.passive: 告诉浏览器你不想阻止事件的默认行为。
vue
<!-- 阻止单击事件继续传播 -->
<a @click.stop="doThis"></a>
<!-- 提交事件不再重载页面 -->
<form @submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联 -->
<a @click.stop.prevent="doThat"></a>
<!-- 只有修饰符 -->
<form @submit.prevent></form>
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div @click.self="doThat">...</div>按键修饰符 (Key Modifiers)
在监听键盘事件时,我们经常需要检查特定的按键。Vue 允许为 v-on 在监听键盘事件时添加按键修饰符:
vue
<!-- 只有在 `key` 是 `Enter` 时调用 `submit` -->
<input @keyup.enter="submit">Vue 为最常用的按键提供了别名:
.enter.tab.delete(捕获“删除”和“退格”键).esc.space.up.down.left.right
你还可以直接使用任何有效的按键名称作为修饰符,例如 @keyup.page-down。