1. 程式人生 > >【mpvue】實現echarts圖表動態載入資料

【mpvue】實現echarts圖表動態載入資料

功能描述

使用mpvue框架開發微信小程式。目的效果為小程式中顯示一個折線圖,當點選切換按鈕時,切換圖表。

實現步驟

1.查詢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()
      }
    }
...

最終效果