vue中使用echarts

3,215 阅读1分钟

引入echarts

npm install echarts --save
或是
yarn add echarts --save
然后在需要的组件中引入
import echarts from "echarts"

使用

html
<div class="envy-pie">
    <div id="envyPie" style="width:90%; height:350px;"></div>
</div>
js
<script>
import echarts from "echarts";
  export default {
    name: 'envyPie',
    props: {
      voltage: Array
    },
    methods: {
      drawPieChart() {
        const this_ = this;
        this.chartPie = echarts.init(document.getElementById("envyPie"));
        this.chartPie.setOption({
          color: ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273'],
          title: {
              text: '装机容量分布情况',
              x: 'center'
          },
          tooltip: {
              trigger: 'item',
              formatter: "{a} <br/>{b} : {c} ({d}%)"
          },
          legend: {
              orient: 'vertical',
              left: 'left',
          },
          series: [{
              name: '装机容量分布情况',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: this_.voltage,
              itemStyle: {
                  emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
              }
          }]
        });
      },
      drawCharts() {
        this.drawPieChart();
      }
    },
    mounted: function() {
      this.drawCharts();
    }

  }
</script>

产生的问题

问题:父子组件传值,容易造成点开子组件后,echarts图不出现

原因:因此在另一个父组件进行应用的时候,他是首屏就加载,数据不变动。但是当数据变动之后,无法自动的更新图表。由于 mounted 只会在挂载的时候执行一次,因此无法后续进行更新。

解决办法:给父组件加上一个v-if,使子组件重新渲染

html
<envy-pie :voltage="voltage" v-if="flag">
js
data () {
      return {
        voltage: [],
        flag: false
      }
    },
    components: {
      envyPie
    },
    methods: {
      getEnvyContent () {
        axios.get('../../../static/mock/envy.json').then(this.getEnvyContentSucc)
      },
      getEnvyContentSucc (res) {
        if (res) {
          const data = res.data
          this.voltage = res.data.capacity_by_voltage
          this.flag = true
        }
      }
    },
    mounted() {
      this.getEnvyContent()
    }

这样解决了。