需求描述
以数据的最小值为基准
- 当最小值超过1分钟时,y轴单位显示“分”
- 当最小值超过1小时时,y轴单位显示“时”
最终效果
实现思路
在向图表传入数据前,对y轴数据做解析,根据y轴数据最小值的大小,得对应的单位,并对y轴数据根据最终显示的单位进行相应的换算,最终将单位和换算过后的y轴数据,传入图表中显示。
完整范例代码
主页 index.vue
<template> <div class="chartBox"> <Bar1 :data="bar1Data" :unit="bar1Unit" /> </div> </template> <script> import Bar1 from "@/pages/chartsDemo/chartsLib/bar1.vue"; export default { components: { Bar1 }, mounted() { this.bar1Data.xList = [ "周一", "周二", "周三", "周四", "周五", "周六", "周天", ]; this.bar1Data.yList = [12000, 20000, 15000, 8000, 7000, 11000, 13000]; this.bar1Unit = this.getUnit(this.bar1Data); }, methods: { getUnit(data) { let min = Math.min(...data.yList); if (min >= 3600) { data.yList = data.yList.map((item) => { return (item / 3600).toFixed(2); }); return "时"; } else if (min >= 60) { data.yList = data.yList.map((item) => { return (item / 60).toFixed(2); }); return "分"; } else { return "秒"; } }, }, data() { return { bar1Data: {}, bar1Unit: "", }; }, }; </script> <style scoped> .chartBox { height: 300px; width: 600px; } </style>
图表组件
src\pages\chartsDemo\chartsLib\bar1.vue
<template> <div style="height: 100%;width: 100%" ref="myChart"></div> </template> <script> import echarts from "echarts"; export default { props: { data: Object, unit: String, }, mounted() { this.$nextTick(() => { this.drawChart(); }); }, methods: { drawChart() { let option = { tooltip: { trigger: "axis", axisPointer: { type: "shadow", }, backgroundColor: "rgba(9, 24, 48, 0.5)", borderColor: "rgba(75, 253, 238, 0.4)", textStyle: { color: "#fff", }, }, legend: { data: ["阅读时长"], right: 60, textStyle: {}, }, xAxis: { type: "category", data: this.data.xList, }, yAxis: { type: "value", name: this.unit, nameLocation: "end", //坐标位置,支持start,end,middle nameTextStyle: { padding: [0, 0, 0, -30], //调整距离坐标位置的距离 }, }, series: [ { name: "阅读时长", data: this.data.yList, type: "bar", }, ], }; // 2.创建图表 let chart = echarts.init(this.$refs.myChart); // 3,导入图表的配置 chart.setOption(option); // 4添加窗口大小改变监听事件,当窗口大小改变时,图表会重新绘制,自适应窗口大小 window.addEventListener("resize", function() { chart.resize(); }); }, }, }; </script> <style scoped></style>