天天看點

【mpvue】實作echarts圖表動态加載資料

功能描述

使用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()
      }
    }
...
           

最終效果

【mpvue】實作echarts圖表動态加載資料
【mpvue】實作echarts圖表動态加載資料