122 lines
3.8 KiB
TypeScript
122 lines
3.8 KiB
TypeScript
import { SHAPES, ShapeCard } from '../../constants/shapes';
|
|
|
|
Component({
|
|
options: {},
|
|
/**
|
|
* 组件的属性列表
|
|
*/
|
|
properties: {
|
|
show: {
|
|
type: Boolean,
|
|
value: false,
|
|
},
|
|
selectedShapeIndex: {
|
|
type: Number,
|
|
value: -1,
|
|
},
|
|
},
|
|
/**
|
|
* 组件的初始数据
|
|
*/
|
|
data: {
|
|
shapes: [] as (ShapeCard & { svgDataUrl: string })[],
|
|
singleMode: false,
|
|
totalSelected: 0,
|
|
},
|
|
lifetimes: {
|
|
attached() {
|
|
// 处理 SVG 数据,转换为 data URL
|
|
const shapesWithDataUrl = SHAPES.map(shape => {
|
|
const completeSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">${shape.svg}</svg>`;
|
|
const svgDataUri = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(completeSvg)}`;
|
|
return {
|
|
...shape,
|
|
svgDataUrl: svgDataUri
|
|
};
|
|
});
|
|
this.setData({
|
|
shapes: shapesWithDataUrl
|
|
});
|
|
}
|
|
},
|
|
observers: {
|
|
selectedShapeIndex(newVal: number) {
|
|
this.setData({
|
|
singleMode: newVal !== -1
|
|
});
|
|
},
|
|
},
|
|
// pageLifetimes: {
|
|
// show: function () {
|
|
// console.log('show singleMode', this.data.singleMode);
|
|
// },
|
|
// hide: function () {
|
|
// console.log('hide singleMode', this.data.singleMode);
|
|
// },
|
|
// resize: function (size) {
|
|
// console.log('resize', size);
|
|
// }
|
|
// },
|
|
/**
|
|
* 组件的方法列表
|
|
*/
|
|
methods: {
|
|
onClose() {
|
|
this.triggerEvent('onClose');
|
|
},
|
|
|
|
onSelectShape(e: WechatMiniprogram.TouchEvent) {
|
|
const { index } = e.currentTarget.dataset;
|
|
const { singleMode, shapes } = this.data;
|
|
let newShapes = [];
|
|
|
|
if (singleMode) {
|
|
// 单选模式:currentShapeKey 不为空时,只能选中一个形状
|
|
newShapes = shapes.map((item, i) => ({
|
|
...item,
|
|
checked: i === index
|
|
}));
|
|
} else {
|
|
// 多选模式:currentShapeKey 为空时,支持多选,最多可选6个
|
|
newShapes = this.data.shapes.map(item => ({ ...item }));
|
|
const targetIndex = index;
|
|
|
|
// 统计当前已选中的数量
|
|
const checkedCount = newShapes.filter(item => item.checked).length;
|
|
|
|
if (newShapes[targetIndex].checked) {
|
|
// 如果已选中,则取消选中
|
|
newShapes[targetIndex].checked = false;
|
|
} else {
|
|
if (checkedCount >= 6) {
|
|
wx.showToast({
|
|
title: '最多可选择6个形状',
|
|
icon: 'none',
|
|
duration: 1500
|
|
});
|
|
return;
|
|
}
|
|
// 如果未选中,则添加到选中列表
|
|
newShapes[targetIndex].checked = true;
|
|
}
|
|
}
|
|
const totalSelected = newShapes.filter(item => item.checked).length;
|
|
this.setData({
|
|
shapes: newShapes,
|
|
totalSelected,
|
|
});
|
|
},
|
|
|
|
onChange() {
|
|
const { shapes, selectedShapeIndex, singleMode } = this.data;
|
|
const selectedShapes = shapes.filter(item => item.checked);
|
|
|
|
this.triggerEvent('onChange', {
|
|
shapes: selectedShapes,
|
|
singleMode,
|
|
selectedShapeIndex
|
|
});
|
|
},
|
|
},
|
|
});
|