// 递归的获取obj中的prop属性 解决有时需要取val.obj.prop的情况 function getPropValueLoop(obj, prop) { if (typeof prop !== 'string') { return obj; } const props = prop.split('.'); let result = obj; props.forEach((item) => { result = result[item]; }); return result; } function getCount(array, element) { let count = 0; array.forEach((e) => { if (e == element) { count++; } }); return count; } export default { getPieChartByDataAndProp(data, prop, label) { let chartData = [] function addNewName(name) { chartData.push({ name: name, value: 1 }) } function addCount(name) { chartData.map(item=>{ if (item.name === name) { item.value++ } }) } function hasThisName(name) { for (let index = 0; index < chartData.length; index++) { const element = chartData[index]; if (element.name === name) { return true } } return false } data .map((item) => { const name = getPropValueLoop(item, prop) if (hasThisName(name)) { addCount(name) }else { addNewName(name) } }) return { title: { text: label, left: 'center' }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left' }, series: [ { type: 'pie', radius: '50%', data: chartData, emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; }, getChartByDataAndProp(data, prop, label, chartType = 'bar') { let series = data.map((item) => getPropValueLoop(item, prop)); const option = { title: { text: label //设置标题 }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left' }, xAxis: { type: 'category', data: Array.from(new Set(series)), axisLabel: { rotate: 45, // 旋转标签,避免重叠 // 或者 interval: 0 // 显示所有标签,可能导致重叠,根据需求调整 } }, yAxis: { type: 'value' }, series: [ { data: Array.from(new Set(series)).map((item) => getCount(series, item) ), type: chartType, smooth: true } ] }; return option; } };