在 Vue 中移除多个事件监听器,核心思路是 “集中管理事件与回调的关联关系,在合适时机批量遍历移除”,避免遗漏或重复操作。以下是具体实现方法,覆盖 Vue 3 和 Vue 2 场景:
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
const btnRef = ref(null);
const events = [
{ type: 'click', handler: handleClick },
{ type: 'mouseenter', handler: handleMouseEnter }
];
function handleClick() { /* ... */ }
function handleMouseEnter() { /* ... */ }
onMounted(() => {
events.forEach(({ type, handler }) => {
btnRef.value?.addEventListener(type, handler);
});
});
onUnmounted(() => {
events.forEach(({ type, handler }) => {
btnRef.value?.removeEventListener(type, handler);
});
});
</script>
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
const boxRef = ref(null);
const eventMap = new Map([
['mousedown', handleMouseDown],
['mousemove', handleMouseMove],
['mouseup', handleMouseUp]
]);
function handleMouseDown() { /* ... */ }
function handleMouseMove() { /* ... */ }
function handleMouseUp() { /* ... */ }
onMounted(() => {
eventMap.forEach((handler, type) => {
boxRef.value?.addEventListener(type, handler);
});
});
onUnmounted(() => {
eventMap.forEach((handler, type) => {
boxRef.value?.removeEventListener(type, handler);
});
});
</script>
export default {
data() {
return {
eventListeners: [
{ el: 'window', type: 'scroll', handler: this.handleScroll },
{ el: 'document', type: 'click', handler: this.handleClick }
]
};
},
methods: {
handleScroll() { },
handleClick() { }
},
mounted() {
this.eventListeners.forEach(({ el, type, handler }) => {
const target = el === 'window' ? window : document;
target.addEventListener(type, handler);
});
},
beforeDestroy() {
this.eventListeners.forEach(({ el, type, handler }) => {
const target = el === 'window' ? window : document;
target.removeEventListener(type, handler);
});
}
};
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
const chartRef = ref(null);
let chart = null;
// ECharts 事件映射
const chartEvents = [
['click', handleChartClick],
['legendselectchanged', handleLegendChange]
];
function handleChartClick() { /* ... */ }
function handleLegendChange() { /* ... */ }
onMounted(() => {
chart = echarts.init(chartRef.value);
chartEvents.forEach(([type, handler]) => {
chart.on(type, handler);
});
});
onUnmounted(() => {
chartEvents.forEach(([type, handler]) => {
chart.off(type, handler);
});
chart.dispose();
});
</script>
-
确保回调函数引用一致
- 错误:用匿名函数绑定
- 正确:用具名函数或
useCallback 缓存
-
捕获阶段参数匹配
el.addEventListener('click', handler, true);
el.removeEventListener('click', handler, true);
-
动态元素的事件委托
对 v-for 列表,优先用事件委托减少监听:
<ul @click="handleItemClick">
<li v-for="item in list" :data-id="item.id">{{ item.name }}</li>
</ul>
- 管理方式:用数组 / Map 存储事件配置,集中管理
- 移除时机:Vue 3 在
onUnmounted,Vue 2 在 beforeDestroy
- 核心原则:绑定与移除的参数(类型、回调、捕获阶段)必须完全一致
|