vue Echarts饼图指定颜色与数据对应

vue Echarts饼图指定颜色与数据对应_第1张图片
需求:一般自定义颜色是按照数据的顺序依次对应,现在想要指定字段对应某个颜色

因为是直接在返回数据中做操作,所以直接写这部分的代码

数据格式

 cdata: {
        xData: ["水文", "森林", "气象", "地质",  "其他"],
        seriesData: [
          { value: 35, name: "水文" ,itemStyle: {color:"#9fe6b8"}},//需要添加color字段
          { value: 15, name: "森林" },//原来的数据格式
          { value: 15, name: "气象" },
          { value: 25, name: "地质" },
          { value: 40, name: "其他" }
        ]
      },

添加字段指定颜色

coloritem:{
        "森林":"#9fe6b8",
        "气象":"#0099ff",
        "水文":"#32c5e9",
        "地质":"#e7bcf3",
        "其他":"#fb7293"
      }

在方法中

 methods: {
    getBar(){
      this.$axios.post('******').then((res)=>{
        let items=res.data //接收到的数据
        this.cdata.seriesData=this.getData(items) //变成想要的数据格式方法
        console.log(this.cdata.seriesData)
      })
    },
    getData(data) {
      let that=this
      return data.map(function (item) {
        return {
          value: item.value,
          name: item.name,
          itemStyle: {
            color: that.coloritem[item.name] // 使用颜色映射表中对应的颜色
          }
       };
     });
    }
 }

然后再把数据传入饼图中,入最上面的图所示,即使数据顺序不同颜色也能对应上了

你可能感兴趣的:(vue.js,echarts,前端)