Component({ /** * 组件的属性列表 */ properties: { index: { type: Number, value: 0, }, svg: { type: String, value: '', }, fillColor: { type: String, value: '', }, }, /** * 组件的初始数据 */ data: { svgDataUri: '', }, /** * 组件生命周期 */ lifetimes: { attached() { this.generateSvgDataUri(); }, }, /** * 监听属性变化 */ observers: { 'svg, fillColor': function () { this.generateSvgDataUri(); } }, /** * 组件的方法列表 */ methods: { /** * 生成完整的 SVG Data URI */ generateSvgDataUri() { const { svg, fillColor } = this.data; if (fillColor === 'transparent') return; if (!svg) return; // 处理 fill 属性:无论原来有没有 fill,都要赋值为 fillColor let processedSvg = svg; // 1. 如果有 fill 属性,全部替换为 fillColor if (/fill="[^"]*"/.test(processedSvg)) { processedSvg = processedSvg.replace(/fill="[^"]*"/g, `fill="${fillColor || '#ff0000'}"`); } else { // 2. 没有 fill 属性,则在第一个标签内加上 fill processedSvg = processedSvg.replace( /(<(?:circle|rect|polygon|ellipse|path|line)[^>]*?)(\/?>)/, `$1 fill="${fillColor || '#ff0000'}"$2` ); } const completeSvg = `${processedSvg}`; // 转换为 Data URI const svgDataUri = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(completeSvg)}`; this.setData({ svgDataUri: svgDataUri }); }, onDelete() { const { index } = this.data; this.triggerEvent('onDelete', { index }); }, onColorTap() { const { index, fillColor } = this.data; console.log('onColorTap', index, fillColor); this.triggerEvent('onColorTap', { index, fillColor }); }, onShapeTap() { const { index } = this.data; this.triggerEvent('onShapeTap', { index }); }, }, });