Vue 的事件机制主要包含以下几种类型和方式,可以分为组件内部事件、父子组件通信事件、原生 DOM 事件封装、修饰符增强等,下面详细分类介绍:
一、DOM 事件绑定(最基础的事件)
使用 v-on
(或简写 @
)指令绑定原生 DOM 事件。
ini
<button @click="handleClick">点击我</button>
二、自定义事件(组件通信)
1. 子组件通过 $emit
向父组件传递事件
子组件中:
xml
<template>
<button @click="$emit('custom-event', data)">发送事件</button>
</template>
父组件中:
ini
<ChildComponent @custom-event="handleCustomEvent" />
2. 使用 v-model
进行双向绑定(语法糖)
Vue3 中可以绑定自定义 modelValue
和 update:modelValue
:
子组件:
xml
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>
<script>
export default {
props: ['modelValue']
}
</script>
父组件:
ini
<ChildComponent v-model="inputValue" />
三、事件修饰符
Vue 为事件添加了很多修饰符,用于增强行为:
.stop
:阻止事件冒泡.prevent
:阻止默认行为.capture
:使用事件捕获模式.self
:只有事件是从绑定元素本身触发才触发.once
:事件只触发一次.passive
:使用被动监听器,适合滚动性能优化
arduino
<button @click.stop.prevent="handleClick">点我</button>
四、键盘事件修饰符
ini
<input @keyup.enter="submit" />
还支持 .esc
, .tab
, .delete
, .arrow-up
, .space
等等。
五、事件代理(原生方式)
在 Vue 中仍然可以使用事件代理:
ruby
<ul @click="handleListClick">
<li v-for="item in list" :key="item.id" :data-id="item.id">{{ item.name }}</li>
</ul>
六、 <math xmlns="http://www.w3.org/1998/Math/MathML"> o n / on / </math>on/off / $emit(Vue2 中的全局事件总线)
Vue2 可以通过事件总线实现跨组件通信:
php
// event-bus.js
export const EventBus = new Vue();
// 发送事件
EventBus.$emit('someEvent', data);
// 接收事件
EventBus.$on('someEvent', data => { ... });
// 移除事件
EventBus.$off('someEvent');
⚠️ Vue3 中已经废弃 $on
/ $off
/ $emit
,推荐使用 mitt
或 emitter
等库替代。
七、Vue3 中的事件通信方式
Vue3 推荐使用以下方式进行事件通信:
defineEmits()
(组合式 API)mitt
第三方事件库provide/inject
Pinia
或Vuex
状态管理emits
选项配合defineProps
ini
// 子组件
const emit = defineEmits(['save']);
emit('save', payload);
八、自定义指令事件
Vue 允许你通过自定义指令实现特殊事件处理逻辑:
javascript
app.directive('click-outside', {
mounted(el, binding) {
document.addEventListener('click', (e) => {
if (!el.contains(e.target)) {
binding.value(e)
}
});
}
});
需要我帮你整理一个"Vue 事件机制脑图"或"快速参考表"吗?