電商篩選、數據儀表盤常見「已選條件」區塊,需實現:用戶點選條件 → 標籤顯示在已選區 → 點擊標籤「×」移除條件 → 列表聯動刷新。核心在於單一數據源驅動多視圖同步。
// 統一狀態管理
const state = {
selected: new Map() // key: 維度名, value: Set(選中值)
// 例: { brand: Set(['Apple','Samsung']), price: Set(['1000-2000']) }
};
// 添加條件
function addCondition(dimension, value) {
if (!state.selected.has(dimension)) state.selected.set(dimension, new Set());
state.selected.get(dimension).add(value);
renderAll();
}
// 移除條件
function removeCondition(dimension, value) {
const set = state.selected.get(dimension);
if (set) {
set.delete(value);
if (set.size === 0) state.selected.delete(dimension);
renderAll();
}
}
// 渲染「已選條件」標籤區
function renderTags() {
const container = document.getElementById('selected-tags');
container.innerHTML = '';
state.selected.forEach((values, dim) => {
values.forEach(val => {
const tag = document.createElement('span');
tag.className = 'tag';
tag.innerHTML = `${dim}: ${val} `;
container.appendChild(tag);
});
});
// 事件委託綁定移除
container.onclick = e => {
if (e.target.tagName === 'BUTTON') {
removeCondition(e.target.dataset.dim, e.target.dataset.val);
}
};
}
// 渲染篩選面板(高亮已選)
function renderPanels() { /* 根據 state.selected 更新 checkbox/radio 狀態 */ }
// 觸發列表查詢
function fetchList() { /* 將 state.selected 序列化為參數調用 API */ }
// 統一入口
function renderAll() {
renderTags();
renderPanels();
fetchList();
}
Proxy 監聽 state.selected 變化自動觸發渲染fetchList 避免頻繁請求