假设有这样一个需求:使用柱状图横轴不肯定,可能有三个、五个、十个八个柱状图,可是颜色就只有三种,无论有多少种,都是循环使用这三种颜色。咱们先看一下,最终的效果图html
当咱们点击按钮,从新绘制echarts的时候,依然是三种颜色循环使用。
npm下载npm install echarts --save
在main.js中引入并原型上挂载import echarts from 'echarts'
Vue.prototype.$echarts = echarts
vue
<template> <div> <div class="echartsBox" id="main"></div> <el-button size="small" type="primary" @click="change">改变数据表</el-button> </div> </template> <script> export default { data() { return { xData: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"], yData: [115, 198, 88, 77, 99, 123, 176], grid: { // 网格线配置 show: true, lineStyle: { color: ["#e9e9e9"], width: 1, type: "solid", }, }, }; }, watch: { xData() { this.echartsInit(); }, yData() { this.echartsInit(); }, }, mounted() { // 在经过mounted调用让echarts渲染 this.echartsInit(); }, methods: { echartsInit() { let main = document.getElementById("main"); // 获取dom元素做为eacharts的容器 this.$echarts.init(main).setOption({ // 调用echarts方法去绘制echarts图 xAxis: { type: "category", // 类别 data: this.xData, // x轴类别对应的值 splitLine: this.grid, // 给x轴加上网格线 }, yAxis: { type: "value", splitLine: this.grid, // 给y轴加上网格线 }, series: [ { data: this.yData, type: "bar", // 类型为柱状图 barWidth: 40, // 柱状图的宽度 itemStyle: { normal: { barBorderRadius: [20, 20, 0, 0], // 加圆角 对应(顺时针左上,右上,右下,左下) // 这里的color指的是每一个颜色的回调函数 color: function (params) { console.log("颜色参数", params); //这里咱们有七个柱状图,七份数据,因此会打印7次。 // params.dataIndex指的是每一个柱状图的索引下标 分别为0 1 2 3 4 5 6 7 8 9 var colorArr = ["#baf", "#bfa", "#cde"]; //colorArr.length 为3,经过取模的方式就能够循环使用颜色了 return colorArr[params.dataIndex % colorArr.length]; }, }, }, }, ], }); }, change() { // 在点击事件中,直接修改data是能修改为功,可是页面不会有变化,由于数据是改变了,可是 // canvas画图仍是原来的图,因此要监听数据,数据变化,就从新执行一次画图的方法就出效果了 this.xData = ["孙悟空", "猪八戒", "沙和尚", "唐僧"]; this.yData = [55, 66, 77, 88]; }, }, }; </script>
重点是echartsInit()-->series-->itemStyle-->normal-->color的函数的逻辑写法,灵活使用能够实现不少好看的效果,虽然官网给的效果图有点丑,固然具体的一些强大的配置项,仍是要去官网去看api文档。官方传送门附上: https://echarts.apache.org/zh...