Vue中使用Echarts 脱坑

1. 数据问题,不像官方实例所提供的数据直接写在options对应的数据源里,开发中应当是后端接口请求过来的数据,一般来说,会将echarts图标抽成组件的形式,需要的数据源通过父组件传给子组件,但是遇到的问题就是,图表会木有数据的问题(图表会展示出来,但是没有数据,尴尬),这是因为echats实例在dom渲染前没有拿到数据,在子组件中使用watch侦听父组件传过来的数据即可,如果有再挂载dom,这样就做到了页面没数据的问题

2. 图表响应式的问题,因为echarts图表是canvas画布生成的,所以说在创建都没元素的时候就应当指定宽高,但是直接将style属性写死宽高做不到图表的响应式,这时候通过父组件获取到图表的父级宽高传给子组件绑定,然后使用window.onresize() 方法的回调设置响应式图表

 

父组件:

 1 <template>
 2   <div class="home" ref="home">
 3     <echarts :widthheight="style" :echartsData="echartsData"></echarts>
 4   </div>
 5 </template>
 6 
 7 <script>
 8 import echarts from "../components/echarts";
 9 export default {
10   components: {
11     echarts
12   },
13   data() {
14     return {
15       style: {
16         width: "",
17         height: "250px"
18       },
19       echartsData: {} //图的数据
20     };
21   },
22   created() {
23     this.echartsData = {
24       X: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
25       Y: [820, 932, 901, 934, 1290, 1330, 1320]
26     };
27   },
28   mounted() {
29     this.style.width = this.$refs["home"].offsetWidth; //获取父元素的宽度
30   }
31 };
32 </script>
33 
34 <style>
35 .home {
36   margin: 50px;
37   border: 1px solid grey;
38   height: 300px;
39 }
40 </style>

子组件:

<template>
  <div ref="var_echarts" :style="widthheight"></div>
</template>

<script>
export default {
  props: ["widthheight", "echartsData"],
  data() {
    return {
      myChart: {} //用来保存echarts图这个实例
    };
  },
  watch: {
      echartsData: function(newval, oldval) {
          if(newval) {
              this.drawBar();
          }
      }
  },

  mounted() {
    this.$nextTick(() => {
      this.drawBar();
    });
    window.onresize = () => {
      this.myChart.resize(); //跟对屏幕的宽度变化而变化
    };
  },
  methods: {
    drawBar() {
      this.myChart = this.$echarts.init(this.$refs.var_echarts);
      this.myChart.setOption({
        xAxis: {
          type: "category",
          data: this.echartsData.X    //
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            data: this.echartsData.Y,  //
            type: "line"
          }
        ]
      });
    }
  }
};
</script>

 

posted @ 2020-07-28 00:28  顺·  阅读(408)  评论(0编辑  收藏  举报