【mpvue】实现echarts图表动态加载数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hao_0420/article/details/82146336

功能描述

使用mpvue框架开发微信小程序。目的效果为小程序中显示一个折线图,当点击切换按钮时,切换图表。

实现步骤

1.查询mpvue官方文档关于echarts的实现方式------静态加载图表,只加载一次

参考官方文档:在mpvue中使用echarts小程序组件

2.实现动态加载图表(能够根据需求多次绘制图表)

思路:每次获取到option(图表数据)的时候就重新绘制一次图表。

实现方法:echarts在此处的使用是以自定义组件的方式来使用的。微信小程序的官方文档中关于自定义组件的介绍中,observer 表示属性值被更改时的响应函数。则在ec-canvas.js中加入该属性,用于判断option(图表数据)更改,重新绘制图表

代码

源码

my-echarts-demo\src\pages\bar\index.vue

<template>
  <div class="counter-warp">
    <button @click="changeEcharts">切换</button>
    <wx-echarts :options = 'wxOptions'></wx-echarts>
    <!--<div class="container">-->
      <!--<ec-canvas class="canvas" id="mychart-dom-bar" canvas-id="mychart-bar" :ec="ec"></ec-canvas>-->
    <!--</div>-->
  </div>
</template>

<script>
import wxEcharts from '../../component/wx-echarts'

const data = [
  [1290, 1330, 1320, 820, 932, 901, 934],
  [934, 934, 934, 934, 934, 932, 901]
]
let i = 0

export default {
  components: {
    wxEcharts
  },
  data () {
    return {
      wxOptions: this.getOptions(0)
    }
  },
  mounted () {
  },
  methods: {
    changeEcharts: function () {
      if (i) {
        i = 0
      } else {
        i = 1
      }
      setTimeout(() => {
        this.wxOptions = this.getOptions(i)
      }, 3000)
    },
    getOptions: function (i) {
      let option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data[i],
          type: 'line'
        }]
      }
      return option
    }
  }
}
</script>

<style>

</style>

my-echarts-demo\src\component\wx-echarts.vue

<template>
  <div class="vital-chart-wx">
    <div>wx-echarts</div>
    <div class="my-charts">
      <ec-canvas  class="canvas" id="mychart" canvas-id="mychart-bar" :ec="ec"></ec-canvas>
    </div>
  </div>
</template>

<script>
  export default {
    props: ['options'],
    data () {
      return {
        ec: {
          options: this.options
        }
      }
    },
    watch: {
      options: {
        handler (newValue, oldValue) {
          this.getOptions(newValue)
        },
        deep: true
      }
    },
    created () {
    },
    mounted () {
    },
    methods: {
      getOptions: function (newValue) {
        this.ec.options = newValue
      }
    }
  }
</script>

<style>
  .my-charts{
    height: 500px;
  }
  ec-canvas {
    width: 300px;
    height: 300px;
  }
</style>

my-echarts-demo\static\ec-canvas\ec-canvas.js

...
ec: {
      type: Object,
      observer: function () {
        this.init()
      }
    }
...

最终效果

    

猜你喜欢

转载自blog.csdn.net/hao_0420/article/details/82146336