解决echarts饼图---legend显示/隐藏饼图不重新计算的问题
利用 formatter 闭包捕获 this,从 chart.getOption() 读取 legend 选中状态。
1. 顶部加 const self = this
initChart() { const self = this // ← 新增 this.chart = echarts.init(this.$refs.pieChart) ...2. 替换 tooltip formatter
// 原 formatter: function(params) { return '<strong>' + params.name + '</strong><br/>' + '工时: ' + params.value.toFixed(1) + ' h<br/>' + '占比: ' + params.percent + '%' } // 新 formatter: function(params) { const option = self.chart.getOption() const selected = option.legend?.[0]?.selected ?? {} const allData = self.data const visible = allData.filter(d => selected[d.name] !== false) const total = visible.reduce((s, d) => s + (d.value || 0), 0) const pct = total ? (params.value / total * 100).toFixed(1) : '0.0' return '<strong>' + params.name + '</strong><br/>' + '工时: ' + params.value.toFixed(1) + ' h<br/>' + '占比: ' + pct + '%' }3. 替换 label formatter(字符串 → 函数)
// 原 label: { show: true, formatter: '{b}\n{c} h ({d}%)', fontSize: 12, fontWeight: 500 } // 新 label: { show: true, formatter: function(params) { const option = self.chart.getOption() const selected = option.legend?.[0]?.selected ?? {} const allData = self.data const visible = allData.filter(d => selected[d.name] !== false) const total = visible.reduce((s, d) => s + (d.value || 0), 0) const pct = total ? (params.value / total * 100).toFixed(1) : '0.0' return params.name + '\n' + params.value.toFixed(1) + ' h (' + pct + '%)' }, fontSize: 12, fontWeight: 500 }效果图
