关于echarts多选下拉框更改折线图数量变更y轴数量

在这里插入图片描述

<template>
  <div class="table-wrapper">
    <Row>
      <Col span="3" offset="16">
        <place-select v-model="areaCode"></place-select>
      </Col>
      <Col span="4" offset="1">
        <DatePicker
          type="daterange"
          :value="time"
          @on-change="kqDateChange"
          :options="pickerOptions"
          placeholder="请选择"
          transfer
        ></DatePicker>
      </Col>
    </Row>
    <trendStatisticsType :time1="time" :areaCode1="areaCode"></trendStatisticsType>
    <statisticalList :time1="time" :areaCode1="areaCode"></statisticalList>
    <div class="trend-statistics-wrapper">
      <div class="choose-container">
        <DatePicker type="daterange" show-week-numbers placement="bottom-end" placeholder="请选择日期" style="width: 200px" @on-change="changeDateHandle"></DatePicker>
        <Select v-model="targetValue" multiple style="width:560px" class="select-self" @on-change="changeHandle">
            <Option v-for="item in targetValueList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </div>
      <div class="chart-container">
        <div class="fchart-bi" style="height: 455px" ref="chartLine" v-if="displayVis">出勤统计</div>
      </div>
    </div>
  </div>
</template>
<script>
import trendStatisticsType from "./trendStatisticsType";
import statisticalList from "./statisticalList";
import { format } from "../../../utils/forMat";
import tableMixin from "@/components/tableMixin";
let echarts = require('echarts');
let nameRateArr = ['项目更新率','项目停工率','项目经理到岗率','项目总监到岗率','项目经理和总监理工程师到岗率']
export default {
mixins: [tableMixin],
  data() {
    return {
      chartLine:null,
      displayVis:true,
      optionObj:{
                legend: {
                  type:'scroll',
                  orient: 'horizontal',
                  top:5,
                  left:80
                },
                tooltip: {
                  axisPointer: {
                    type: 'shadow'
                  },
                  trigger: 'axis',
                  formatter: function(params) {
                  let str = '';
                  params.forEach((item,idx) => {
                    str += `${item.marker}${item.seriesName}: ${item.data}`
                    if(nameRateArr.includes(item.seriesName)){
                     str += '%';
                    }
                    str += idx === params.length -1? '': '<br/>'
                  })
                  return str
                }
                },
                grid:{
                    left: 60,
                    right:60,
                    top: 40,
                    bottom: 40,
                },
                xAxis:{
                    name:'日期',
                    nameTextStyle:{
                        align:'right',
                        padding:[30,0,0,0]
                    },
                    /* 类目轴*/
                    type:'category',
                    axisLabel:{
                        interval:0,
                    },
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: []
                },
                yAxis:[
                ],
                series: [
                ]
      },
      timeValueArr:[],
      targetValue:['atendanceProjectsuperviseRate','projectStopRate'],
      rateArr:['atendanceProjectsuperviseRate','projectStopRate','buildManagerAverageToPostRate','supervisionManagerAverageToPostRate','managerAndChiefInspectorAttendanceRate'],
      targetValueList:[
         {
              value: 'atendanceProjectsuperviseRate',
              label: '项目更新率'
          },
           {
              value: 'projectStopRate',
              label: '项目停工率'
          },
          {
              value: 'hasAttendanceProjectCount',
              label: '有考勤项目的平均上班工人数'
          },
          {
              value: 'buildManagerAverageToPostRate',
              label: '项目经理到岗率'
          },
           {
              value: 'supervisionManagerAverageToPostRate',
              label: '项目总监到岗率'
          },
          {
              value: 'managerAndChiefInspectorAttendanceRate',
              label: '项目经理和总监理工程师到岗率'
          },
          {
              value: 'notSetProjectManagersNum',
              label: '未设置项目经理的项目数'
          },
          {
              value: 'notSetProjectDirectorNum',
              label: '未设置总监理工程师的项目数'
          },
          {
              value: 'setProjectManagersNotCertifiedArchitectNum',
              label: '无效项目经理项目数'
          },
          {
              value: 'setProjectDirectorNotRegisteredSupervisorNum',
              label: '无效总监理工程师项目数'
          },
           {
              value: 'projectExceedNoCheckMessageNum',
              label: '项目超期未审核预警'
          },
           {
              value: 'supplierExceedNoJointMessageNum',
              label: '供应商超期未联调预警'
          },
      ],
      countArr:['hasAttendanceProjectCount','notSetProjectManagersNum','notSetProjectDirectorNum','setProjectManagersNotCertifiedArchitectNum','setProjectDirectorNotRegisteredSupervisorNum','projectExceedNoCheckMessageNum','supplierExceedNoJointMessageNum'],
      time: [],
      singleOrdouble:false,
      areaCode: this.common.getTenantAreaCode(),
      resultArr:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 24 * 60 * 60 * 1000;
        },
      },
    };
  },
  components: {
    trendStatisticsType,
    statisticalList,
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
          //引入echarts 初始化图标
      // 工资发放情况
      this.chartLine = echarts.init(this.$refs.chartLine);
      this.queryTrendStatisticsLineData()
      window.addEventListener('resize',this.resize);
      window.addEventListener('load',this.resize);
      /*加载完成自适应*/
      this.$nextTick( ()=> {
          this.resize();
      });
  },
  methods: {
    // echarts 适应
    resize(){
        this.chartLine.resize();
    },
    // 人员出勤监管查询
    queryTrendStatisticsLineData(){
        this.chartLine.showLoading();
        this.axios({
            method: 'post',
            url: '/gd/trendStatistics/queryTrendStatisticsLineData',
            data:{
                "areaCode":localStorage.getItem('tenantAreaCode'),
                "areaType":localStorage.getItem('areaType'),
                "startDate":this.timeValueArr.length > 0 ? this.timeValueArr[0] : this.$moment(new Date().getTime() - 29*24*60*60*1000).format('YYYY-MM-DD'),
                "endDate":this.timeValueArr.length > 0 ? this.timeValueArr[1] : this.$moment(new Date()).format('YYYY-MM-DD')
            }
        }).then( (response)=> {
            if (response.data.data){
              this.resultArr = response.data.data
                let xData=[];
                this.resultArr.forEach(item=>{
                    xData.push(item.workDate);
                });
                this.optionObj.xAxis.data = xData
                this.handleyYAxis()
                this.handleySeries()
                this.optionObj.dataZoom = xData.length > 15 ? [
                            {
                                startValue : 0,
                                endValue : 10,
                                type: 'slider',
                                show: true,
                                xAxisIndex: [0],
                                height: 10,
                                bottom: 8,
                                borderRadius: 5,
                                showDataShadow: false,
                                showDetail: false,
                                realtime: true
                            }
                        ] : []
                this.chartLine.setOption(this.optionObj);
                this.chartLine.hideLoading();
            }
        });
    },
    handleySeries(){
      let series = []
      this.targetValue.forEach(item=>{
         let dataArr = this.resultArr.map(ele=>{
           if(ele[item] && ele[item].toString().includes('%')){
             ele[item] = ele[item].replace('%','')
           }
           return ele[item]*1
         })
         let name = this.targetValueList.filter(k=>k.value == item)[0].label
         let obj = {
              type: 'line',
              name: name,
              keyValue:item,
              yAxisIndex: 1, //使用的 y 轴的 index,在单个图表实例中存在多个 y轴的时候有用。
              data:dataArr,
          }
         if(this.singleOrdouble){
           if(this.countArr.includes(item)){
             obj['yAxisIndex'] = 0
           }
         } else {
           delete obj.yAxisIndex
         }
          series.push(obj)
      })
      this.optionObj.series = series
    },
    handleyYAxis(){
      this.optionObj.yAxis = []
      let flagCount = this.targetValue.some(item=>{
         return this.countArr.includes(item) 
      })
      if(flagCount){
        this.optionObj.yAxis.push({
                    name:'数量',
                    type:'value',
                    splitLine: {
                        show: true, //网格线开关
                        lineStyle:{
                            type:'dashed'
                        },
                        axisLine:{
                            show: false
                        },
                    },
                    axisLine:{
                        show: false
                    },
                    minInterval: 1,
                    })
      }
      let flagRate = this.targetValue.some(item=>{
         return this.rateArr.includes(item) 
      })
      if(flagRate){
        this.optionObj.yAxis.push({
                    name:'%',
                    type:'value',
                    // min: 0,
                    // max: 100,
                    splitNumber : 5,
                    splitLine: {
                        show: true, //网格线开关
                        lineStyle:{
                            type:'dashed'
                        },
                        axisLine:{
                            show: false
                        },
                    },
                    axisLine:{
                        show: false
                    },
                    // minInterval: 1,
                    })
      }
      if(flagCount && flagRate){
        this.singleOrdouble = true
      } else {
        this.singleOrdouble = false
      }
    },
    changeDateHandle(e){
      this.timeValueArr = e
      this.queryTrendStatisticsLineData()
    },
    changeHandle(){
      this.chartLine.showLoading();
      this.handleyYAxis()
      this.handleySeries()
      //  增加可以重新绘制echarts但是 减少不会重新绘制 故增加此方法
      document.querySelector('.fchart-bi').removeAttribute('_echarts_instance_')
      this.chartLine = null
      this.chartLine = echarts.init(this.$refs.chartLine);
      console.log(this.optionObj)
      this.chartLine.setOption(this.optionObj);
      this.chartLine.hideLoading();
      // this.displayVis = false
      // this.displayVis = true
      // this.$nextTick(()=>{
      //         this.chartLine = null
      //         this.chartLine = echarts.init(this.$refs.chartLine);
      //         console.log(this.optionObj)
      //         this.chartLine.setOption(this.optionObj);
      //         this.chartLine.hideLoading();
      // })
    },
    kqDateChange(e) {
      console.log(e);
      this.time = e
    },
    getTableData() {
      this.areaCode = this.common.getTenantAreaCode()
      //当前设定的日期时间
      let d = new Date(Date.now() - 86400000);
      //前一天设定的日期时间
      let year2, month2, day2;
      d.setTime(d.getTime());
      [year2, month2, day2] = [d.getFullYear(), d.getMonth(), d.getDate()];
      let timeChanges1 = new Date(year2, month2, day2, 0);
      this.time = [
        format(timeChanges1, "yyyy-MM-dd"),
        format(timeChanges1, "yyyy-MM-dd"),
      ];
      return this.time;
    },
  },
};
</script>
<style lang="less">
.trend-statistics-wrapper{
  .choose-container{
    display: flex;
    justify-content: flex-end;
    .select-self{
      .ivu-select-selection {
          height: 32px;
          overflow: auto;
      }
    }
  }
}
</style>

需要注意点1 变更y轴数量时需要更改 yAxisIndex值
在这里插入图片描述
需要注意点2 增加线条会重绘但是减少不会重绘
在这里插入图片描述
3.遇到得坑 少写了一个else 导致 更改yaxindex值发生错误
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值