在 Vue 中确保数组 / 对象中存储的事件配置唯一性,核心是 **“给每个事件配置分配唯一标识(ID),并通过 ID 管理配置的增删改查,避免重复添加”**。以下是具体实现方法,覆盖静态配置和动态配置场景:
const eventConfig = [
{
id: Symbol('click-event'),
type: 'click',
handler: handleClick
},
{
id: Symbol('scroll-event'),
type: 'scroll',
handler: handleScroll
}
];
import { v4 as uuidv4 } from 'uuid';
const eventConfig = [
{
id: uuidv4(),
type: 'click',
handler: handleClick
}
];
let eventId = 0;
function addEvent(type, handler) {
eventConfig.push({
id: ++eventId,
type,
handler
});
}
const eventConfig = [
{ type: 'click', handler: handleClick },
{ type: 'click', handler: handleClick }
];
const eventConfig = [
{ id: 1, type: 'click', handler: handleClick },
{ id: 2, type: 'scroll', handler: handleScroll }
];
function addUniqueEvent(type, handler) {
const exists = eventConfig.some(
event => event.type === type && event.handler === handler
);
if (!exists) {
eventConfig.push({
id: Date.now(),
type,
handler
});
}
}
const eventMap = new Map();
function addEvent(type, handler) {
const key = `${type}-${handler.name}`;
if (!eventMap.has(key)) {
eventMap.set(key, { type, handler });
}
}
function getEvents() {
return Array.from(eventMap.values());
}
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { v4 as uuidv4 } from 'uuid';
const boxRef = ref(null);
const eventConfig = ref([]);
// 定义事件处理函数
function handleClick() { /* ... */ }
function handleScroll() { /* ... */ }
// 添加唯一事件配置
function addEvent(type, handler) {
const id = uuidv4();
eventConfig.value.push({ id, type, handler });
}
// 初始化事件配置
addEvent('click', handleClick);
addEvent('scroll', handleScroll);
// 绑定事件
onMounted(() => {
eventConfig.value.forEach(({ type, handler }) => {
boxRef.value.addEventListener(type, handler);
});
});
// 移除事件
onUnmounted(() => {
eventConfig.value.forEach(({ type, handler }) => {
boxRef.value.removeEventListener(type, handler);
});
});
</script>
-
不要使用匿名函数
addEvent('click', () => console.log('click'));
function handleClick() { console.log('click'); }
addEvent('click', handleClick);
-
避免重复绑定同一事件
function addEventIfNotExists(type, handler) {
const exists = eventConfig.some(
event => event.type === type && event.handler === handler
);
if (!exists) {
eventConfig.push({ type, handler });
}
}
-
使用不可变数据结构
function addEvent(type, handler) {
eventConfig.value = [...eventConfig.value, { type, handler }];
}
确保数组 / 对象中事件配置的唯一性,关键在于给每个配置项分配唯一标识(如 Symbol、UUID、递增 ID),并在添加时检查是否已存在。这样可以避免重复绑定事件,确保后续移除时能准确匹配,从而有效防止内存泄漏。 |