您的位置:首页技术文章
文章详情页

解决Vue + Echarts 使用markLine标线(precision精度问题)

【字号: 日期:2023-01-02 18:22:04浏览:4作者:猪猪

在VUE实例中使用Echarts

安装echarts依赖:

npm install echarts -s

编写代码:

引入echarts对象:

鉴于准备工作中已经通过npm安装了echarts依赖,所以可以直接在vue文件中使用代码import echarts from “echarts”引入echarts对象:

<script> import echarts from ’echarts/lib/echarts’</script>

注意:只引入了echarts还不能直接使用markLine(作为前端菜鸟爬坑了好久?)

引入markLine对象:

<script> import echarts from ’echarts/lib/echarts’ import ’echarts/lib/component/markLine’</script>

以下是我画图的所有echarts依赖:

import echarts from ’echarts/lib/echarts’ import ’echarts/lib/chart/candlestick’ import ’echarts/lib/chart/bar’ import ’echarts/lib/component/legend’ import ’echarts/lib/component/title’ import ’echarts/lib/component/markLine’

markLine终于有用了?

我的代码:

这是我的markLine配置

let price = [13.9, 14.95, 16];markLine: { symbol: ’none’, silent: true, data: [ {yAxis: price[0]}, {yAxis: price[1]}, {yAxis: price[2]} ], lineStyle: { show: true, color: ’#808C94’, type: ’dashed’ }}

markLine效果:

解决Vue + Echarts 使用markLine标线(precision精度问题)

然而 Echarts 的 series[i]-bar.markLine.precision 配置项不太厚道

Echarts文档中的描述:

series[i]-bar.markLine.precision number

[ default: 2 ]

标线数值的精度,在显示平均值线的时候有用。

根据上图展示,并没有我想要的精度。

——注:13.9应该显示13.90,16应该显示16.00

precision配置默认为2

怎么办?填坑!

仔细翻看Echarts文档发现了一个配置:

series[i]-bar.markLine.label.formatter

里面有个回调函数,而且与axisLabel.formatter不太一样

修改配置一:

请确保你的Number.toFixed(2)是满足要求的

markLine: { symbol: ’none’, silent: true, data: [ {yAxis: price[0]}, {yAxis: price[1]}, {yAxis: price[2]} ], lineStyle: { show: true, color: ’#808C94’, type: ’dashed’ }, // 先让markLine精确到3,默认为2 precision: 3, label: { formatter: function(value) { // 确保你的Number.toFixed(2)是满足要求的 return value.value.toFixed(2); } }}

修改配置二:

markLine: { symbol: ’none’, silent: true, data: [ {yAxis: price[0]}, {yAxis: price[1]}, {yAxis: price[2]} ], lineStyle: { show: true, color: ’#808C94’, type: ’dashed’ }, // 先让markLine精确到3,默认为2 precision: 3, label: { // 没有写通用代码了,针对性解决一下当前问题 formatter: function(value) { // 这里的value 是一个label对象,使用value.value获取到真正的值 let strVal = value.value.toString(); let splitStr = strVal.split(’.’); let tailStr = splitStr[1]; if (tailStr == null) { return value.value.toString() + ’.00’; } // 0.995 ~ 0.999 = 1 if (tailStr >= 995) { return (parseInt(splitStr[0]) + 1).toString() + ’.00’; } if (tailStr.length >= 3) { let lastStr = tailStr.substr(2, 1); // 解决toFixed(2)方法四舍五入无效 if (lastStr >= 5) { // 数值+101有些取巧,但能解决问题... tailStr = (parseInt(tailStr.substr(0, 2)) + 101).toString().substr(1, 2); return splitStr[0] + ’.’ + tailStr; } else { return splitStr[0] + ’.’ + tailStr.substr(0, 2); } } else if (tailStr.length === 1) { return value.value.toString() + ’0’; } else { return value.value.toString(); } } }}

鬼知道Number.toFixed(2)为什么保留两位小数时并没有四舍五入,就写了段恶心的代码,个人能力有限?

修改后效果:

解决Vue + Echarts 使用markLine标线(precision精度问题)

以上这篇解决Vue + Echarts 使用markLine标线(precision精度问题)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Vue
相关文章: