const cityData = [
{code: '110000', name: '北京', children: []},
{code: '310000', name: '上海', children: []},
{code: '440000', name: '廣東', children: [
{code: '440100', name: '廣州'},
{code: '440300', name: '深圳'},
{code: '440400', name: '珠海'}
]},
// ... 所有省市區資料
];
class CityPicker {
constructor(triggerEl, options = {}) {
this.trigger = triggerEl;
this.data = options.data || cityData;
this.value = options.value || null; // {province, city}
this.onChange = options.onChange;
this.isMobile = window.innerWidth < 768;
this.render();
this.bindEvents();
}
render() {
// 建立下拉面板 DOM,掛載 document.body(避免 overflow 截斷)
// 結構:省份列表 + 城市列表(或單列表)
// 使用虛擬滾動:僅渲染可視區 + 緩衝區項目
}
// 虛擬列表核心邏輯
renderVirtualList(container, items, itemHeight, renderItem) {
const scrollTop = container.scrollTop;
const visibleCount = Math.ceil(container.clientHeight / itemHeight);
const start = Math.max(0, Math.floor(scrollTop / itemHeight) - 5);
const end = Math.min(items.length, start + visibleCount + 10);
container.style.paddingTop = `${start * itemHeight}px`;
container.style.paddingBottom = `${(items.length - end) * itemHeight}px`;
const fragment = document.createDocumentFragment();
for (let i = start; i < end; i++) {
fragment.appendChild(renderItem(items[i], i));
}
container.innerHTML = '';
container.appendChild(fragment);
}
}
handleKeydown(e) {
const focused = this.panel.querySelector('[data-focused]');
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
this.focusNext(focused);
break;
case 'ArrowUp':
e.preventDefault();
this.focusPrev(focused);
break;
case 'Enter':
e.preventDefault();
focused?.click();
break;
case 'Escape':
this.close();
this.trigger.focus();
break;
case 'Tab':
if (!this.isMobile) this.close(); // 桌面端 Tab 關閉
break;
}
}
// 觸發按鈕
// 面板
北京
廣州
selectProvince(province) {
this.value = {province, city: null};
this.renderCityList(province.children);
this.updateTriggerText();
if (province.children.length === 0) this.confirm(); // 直轄市直接確認
}
selectCity(city) {
this.value = {...this.value, city};
this.confirm();
}
confirm() {
this.close();
this.onChange?.(this.value);
this.trigger.focus();
}
// Shadow DOM 方案(完全隔離)
this.shadow = this.trigger.attachShadow({mode: 'open'});
this.shadow.adoptedStyleSheets = [cityPickerStylesheet]; // 建構式樣式表
this.shadow.appendChild(this.panel);
const useCityPicker = (props, emit) => {
const panelRef = ref(null);
const provinceList = computed(() => props.data);
const cityList = computed(() => props.value?.province?.children || []);
// ... 虛擬列表、鍵盤導航、ARIA 邏輯
return {panelRef, provinceList, cityList, selectProvince, selectCity};
};
const useCityPicker = (data, onChange) => {
const [province, setProvince] = useState(null);
const [city, setCity] = useState(null);
const [open, setOpen] = useState(false);
// ... 邏輯
return {province, city, open, setOpen, setProvince, setCity};
};
城市選擇器是典型的「看似簡單、實則複雜」UI 組件。優秀實現需兼顧:資料結構設計、虛擬列表效能、鍵盤/無障礙完整支援、響應式佈局、框架無關核心邏輯、樣式隔離。建議採用成熟庫(如 Vant Area、El-Cascader、Antd Cascader)或參考其源碼自建,避免重複造輪子並踩坑。