最近使用echarts做图表,数字位数过多时,在小屏手机会出现数字显示不全,被遮挡的问题。
echarts: "5.4.0",
vue: "3.2.45",
使用科学计数法
//y轴使用科学计数法表示
const echartsYaxisLabelFormatter = (value: any) => {if (Math.abs(value) > 100000) {if (value == 0) {return "0";} else if ((value + '').indexOf('e') > 0) {return (value + '').replace(/e/, "E");} else {let res = value.toString(),numN1 = 0,numN2 = 0,num1 = 0,num2 = 0,t1 = 1for (let k = 0; k < res.length; k++) {if (res[k] == ".")t1 = 0;if (t1)num1++;elsenum2++;}// 均转换为科学计数法表示if (Math.abs(value) < 1) {// 小数点后一位开始计算for (let i = 2; i < res.length; i++) {if (res[i] == "0") {numN2++; //记录10的负指数值(默认值从1开始)} else if (res[i] == ".")continue;elsebreak;}let v: number | string = parseFloat(value);v = v * Math.pow(10, numN2);v = v.toFixed(1); //四舍五入 仅保留一位小数位数return `${v.toString()}e-${numN2}`;} else if (num1 > 1) {numN1 = num1 - 1;let v: number | string = parseFloat(value);v = v / Math.pow(10, numN1);if (num2 > 1) {v = v.toFixed(1);}return `${v.toString()}e${numN1}`;}}} else {return value;}
}
<template><div class="sku-details-echarts"><div ref="historicalPrice_chart" style="height:350px;width:100%;"></div></div>
</template><script setup name="SkuDetailsEcharts" lang="ts">
import { ComponentInternalInstance } from 'vue';
import * as echarts from 'echarts';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const historicalPrice_chart = ref();/********************** 方法调用 **********************/
let resizeObserver: ResizeObserver | null = null,canResize = true,historicalPrice_echarts: echarts.ECharts | null = nullconst initChart = () => {nextTick(() => {// 历史价格historicalPrice_echarts = echarts.init(historicalPrice_chart.value);historicalPrice_echarts.setOption({tooltip: {trigger: 'axis'},grid: {left: '1%',right: '4%',bottom: '3%',containLabel: true},xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value',axisLabel: {formatter: (value: number) => echartsYaxisLabelFormatter(value) //调用科学计数法方法},},series: [{data: ['0','0','41040142.00','363014742873.60','175749696.00','18144044046547.20','0','48448.20','10632.50','5024.00','8414.40'],type: 'line',smooth: true}]})const targetElement = document.getElementsByClassName('hasTagsView')[0];resizeObserver = new ResizeObserver(entries => {if (!canResize) {return}canResize = falsesetTimeout(() => {canResize = trueconsole.log('监听到宽高的变化++++++++++++');historicalPrice_echarts?.resize()}, 500)/* console.log(entries[0].contentRect.width)console.log(entries[0].contentRect.height) */})resizeObserver.observe(targetElement)})
}onUnmounted(() => {// 停止监听给定的元素// resizeObserver?.unobserve(targetElement);// 停止监听所有元素resizeObserver?.disconnect();console.log('卸载了+++++++++++++++++++++');
})onMounted(() => {nextTick(() => {// 销毁echarts实例historicalPrice_echarts?.dispose();// initChart()initChart()})
});
</script><style scoped lang="scss"></style>