Echarts 系列文章:
前言
做大屏、數據可視化的話,圖表類的必不可少。
這其中使用 Echarts 的很多。
一、參數動態返回值
Echarts 中參數的配置功能很強大。對任何一項的配置都很細致。
雖然這樣,但是有時候不一定能到達需求。這時候能根據數據動態改變就好了。
在官方配置項中,formatter 是支持函數回調的。官方的文檔:
formatter: function(params) => string // params 格式: { componentType: 'series', // 系列類型 seriesType: string, // 系列在傳入的 option.series 中的 index seriesIndex: number, // 系列名稱 seriesName: string, // 數據名,類目名 name: string, // 數據在傳入的 data 數組中的 index dataIndex: number, // 傳入的原始數據項 data: Object, // 傳入的數據值。在多數系列下它和 data 相同。在一些系列下是 data 中的分量(如 map、radar 中) value: number|Array|Object, // 坐標軸 encode 映射信息, // key 為坐標軸(如 'x' 'y' 'radius' 'angle' 等) // value 必然為數組,不會為 null/undefied,表示 dimension index 。 // 其內容如: // { // x: [2] // dimension index 為 2 的數據映射到 x 軸 // y: [0] // dimension index 為 0 的數據映射到 y 軸 // } encode: Object, // 維度名列表 dimensionNames: Array<String>, // 數據的維度 index,如 0 或 1 或 2 ... // 僅在雷達圖中使用。 dimensionIndex: number, // 數據圖形的顏色 color: string, }
可以根據當前數據項動態返回。
一般用這個配置的也挺多。
其實其他項也可以這樣配置,到現在驗證了 bar 的 itemStyle 的 color 這樣可行其他不可行。
下面是 bar 類型柱狀顏色:
series: [{ name: '整改情況排名', type: 'bar', itemStyle: { color: function(params) {
// colors 是自定義的顏色數組 var num = colors.length return colors[params.dataIndex % num] } }, data: [] }]
二、綁定 Options 問題
這個是問題是在實際中遇到的。
具體場景:同一個組件中有兩個 Echarts bar 圖表。所以在定義 options 用同一個,在處理數據時再處理:
let tempOption = JSON.parse(JSON.stringify(czOptions)) // 其他處理 this.options = tempOption tempOption = JSON.parse(JSON.stringify(czOptions)) // 其他處理 this.optionsR = tempOption
這樣是簡單的深度拷貝,能使兩個相互獨立出來沒有關聯,互不影響。
但是會把 function 類型的屬性忽略掉(所以上面寫的動態參數無用)
這時就只能在拷貝后再對動態參數賦值:
tempOption.series[0].itemStyle.color = function(params) { var num = colors.length return colors[params.dataIndex % num] }
這樣能正常展示
推薦: