// 递归的获取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 { /** 将chart图表转化为图片url * @param chart: chart图表的实例 * */ chartToImageUrl(chart) { const dataURL = chart.getDataURL({ pixelRatio: 5, // 提高图片质量 backgroundColor: '#FFFFFF', // 设置背景颜色 excludeComponents: ['toolbox'], // 排除工具箱组件 type: 'png' // 输出图片类型为PNG }); return dataURL; }, // 展示 data 数组中对象的 prop 属性的饼图, title 是饼图的标题 getPieChartByDataAndProp(data, prop, label) { let chartData = []; 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)) { chartData.map((item) => { if (item.name === name) { item.value++; } }); } else { chartData.push({ name: name, value: 1 }); } }); 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)' } } } ] }; }, // 展示 data 数组中对象的 prop 属性的直方图, title 是直方图的标题 getBarChartByDataAndProp(data, prop, title) { let series = data.map((item) => getPropValueLoop(item, prop)); const option = { title: { text: title //设置标题 }, 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: 'bar', smooth: true } ] }; return option; } };