class HeaderTools extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.render();
this.addEventListeners();
}
// 添加getter方法
get selectedProduct() {
return this.shadowRoot.getElementById('productSelect').value;
}
render() {
this.shadowRoot.innerHTML = `
构型:
`;
}
addEventListeners() {
// 加载构型列表
this.loadProducts();
// 字体大小调整
this.shadowRoot.getElementById('fontSizeBtn').addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('font-size-click'));
});
// 主题调整
this.shadowRoot.getElementById('themeBtn').addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('theme-click'));
});
// 通知
this.shadowRoot.getElementById('notificationBtn').addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('notification-click'));
});
// 在线用户
this.shadowRoot.getElementById('onlineUsersBtn').addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('online-users-click'));
});
// 构型选择
this.shadowRoot.getElementById('productSelect').addEventListener('change', (e) => {
this.dispatchEvent(new CustomEvent('product-change', {
detail: { product: e.target.value }
}));
});
}
async loadProducts() {
try {
const response = await fetch('/api/products');
if (!response.ok) {
throw new Error('获取构型列表失败');
}
const products = await response.json();
const select = this.shadowRoot.getElementById('productSelect');
// 清空现有选项
select.innerHTML = '';
products.forEach(product => {
const option = document.createElement('option');
option.value = product.ProductName;
option.textContent = product.ProductName;
select.appendChild(option);
});
} catch (error) {
console.error('加载构型列表失败:', error);
// 可以在这里添加错误提示UI
}
}
}
customElements.define('header-tools', HeaderTools);