您的位置:首頁技術文章
文章詳情頁

解決Vue + Echarts 使用markLine標線(precision精度問題)

瀏覽:5日期:2023-01-02 18:22:04

在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
相關文章:
国产综合久久一区二区三区