vue中使用echarts自动设置颜色,根据数据返回的长度来设置以蓝色为主调的颜色,从深到浅
时间: 2024-03-27 15:38:48 浏览: 20
可以通过 ECharts 中提供的 color 数组来设置颜色。你可以使用 Vue 中的计算属性来根据数据长度自动生成颜色数组。以下是一个示例代码:
```html
<template>
<div ref="chart" style="width: 100%; height: 500px;"></div>
</template>
<script>
import echarts from 'echarts'
export default {
data() {
return {
chartData: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
}
},
computed: {
colors() {
const len = this.chartData.length
const colorArr = []
for (let i = 0; i < len; i++) {
const opacity = 1 - i / len
colorArr.push(`rgba(0, 0, 255, ${opacity})`)
}
return colorArr
}
},
mounted() {
const chart = echarts.init(this.$refs.chart)
chart.setOption({
xAxis: {
type: 'category',
data: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
},
yAxis: {
type: 'value'
},
series: [{
data: this.chartData,
type: 'bar',
itemStyle: {
normal: {
color: (params) => {
return this.colors[params.dataIndex]
}
}
}
}]
})
}
}
</script>
```
在上面的代码中,我们使用 computed 计算属性来生成颜色数组。首先获取数据长度 len,然后循环生成颜色数组 colorArr,每个颜色的透明度 opacity 都随着索引值 i 的增加而减小,这样就可以实现从深到浅的渐变效果。最后将颜色数组作为参数传递给柱状图的 itemStyle.normal.color 属性即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)