import { SHAPES, ShapeCard } from '../../constants/shapes'; Component({ options: {}, /** * 组件的属性列表 */ properties: { show: { type: Boolean, value: false, }, selectedShape: { type: String, value: '', }, currentShapeKey: { type: String, value: '', }, }, /** * 组件的初始数据 */ data: { shapes: [] as (ShapeCard & { svgDataUrl: string })[], selectedShapes: [] as string[], // 多选模式下选中的形状数组 }, lifetimes: { attached() { // 处理 SVG 数据,转换为 data URL const shapesWithDataUrl = SHAPES.map(shape => { const completeSvg = `${shape.svg}`; const svgDataUri = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(completeSvg)}`; return { ...shape, svgDataUrl: svgDataUri }; }); console.log('shapesWithDataUrl---:', shapesWithDataUrl); this.setData({ shapes: shapesWithDataUrl }); }, }, /** * 组件的方法列表 */ methods: { onClose() { this.triggerEvent('onClose'); }, onSelectShape(e: WechatMiniprogram.TouchEvent) { const { index } = e.currentTarget.dataset; const { currentShapeKey, shapes } = this.data; if (currentShapeKey) { // 单选模式:currentShapeKey 不为空时,只能选中一个形状 this.setData({ shapes: shapes.map((item, i) => ({ ...item, checked: i === index })) }); } else { // 多选模式:currentShapeKey 为空时,支持多选,最多可选6个 let shapesCopy = this.data.shapes.map(item => ({ ...item })); const targetIndex = index; // 统计当前已选中的数量 const checkedCount = shapesCopy.filter(item => item.checked).length; if (shapesCopy[targetIndex].checked) { // 如果已选中,则取消选中 shapesCopy[targetIndex].checked = false; } else { if (checkedCount >= 6) { wx.showToast({ title: '最多可选择6个形状', icon: 'none', duration: 1500 }); return; } // 如果未选中,则添加到选中列表 shapesCopy[targetIndex].checked = true; } this.setData({ shapes: shapesCopy, }); } }, onChange() { const { selectedShape, selectedShapes, currentShapeKey } = this.data; if (currentShapeKey) { // 单选模式:返回单个选中的形状 this.triggerEvent('onChange', { shape: selectedShape, currentShapeKey }); } else { // 多选模式:返回选中的形状数组 this.triggerEvent('onChange', { shapes: selectedShapes }); } }, // 获取选中状态的 CSS 类名 getShapeClass(shapeId: string): string { const { currentShapeKey, selectedShapes } = this.data; if (currentShapeKey) { // 单选模式:检查是否等于当前选中的形状 return shapeId === currentShapeKey ? 'selected single-mode' : ''; } else { // 多选模式:检查是否在选中列表中 return selectedShapes.includes(shapeId) ? 'selected multi-mode' : ''; } }, }, });