在 Vue 中確保數(shù)組 / 對象中存儲的事件配置唯一性,核心是 **“給每個事件配置分配唯一標識(ID),并通過 ID 管理配置的增刪改查,避免重復添加”**。以下是具體實現(xiàn)方法,覆蓋靜態(tài)配置和動態(tài)配置場景:
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([]);
// 定義事件處理函數(shù)
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>
-
不要使用匿名函數(shù)
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 });
}
}
-
使用不可變數(shù)據(jù)結構
function addEvent(type, handler) {
eventConfig.value = [...eventConfig.value, { type, handler }];
}
確保數(shù)組 / 對象中事件配置的唯一性,關鍵在于給每個配置項分配唯一標識(如 Symbol、UUID、遞增 ID),并在添加時檢查是否已存在。這樣可以避免重復綁定事件,確保后續(xù)移除時能準確匹配,從而有效防止內存泄漏。 |