小程序mpvue中動態切換echarts圖表

若是你用mpvue,並且還想用echarts,那麼這個包你能夠以來一下css

https://github.com/F-loat/mpvue-echartsvue

考慮到多個頁面都休要用,因此抽出來做爲一個組件,總得來講根據官方的例子小改動了一下git

vue文件github

1 <template>
2   <div class="echarts-wrap">
3     <mpvue-echarts :echarts="echarts" :onInit="handleInit" canvasId="getCanvasId" ref="echarts" />
4   </div>
5 </template>
6 
7 <script src="./control.js"></script>
8 
9 <style scoped lang="stylus" src="./style.styl"></style>

js文件canvas

 1 import echarts from 'echarts'
 2 import mpvueEcharts from 'mpvue-echarts'
 3 import { messageTip, wxHideLoading, wxLoading } from "../../utils/wxapi";  4 
 5 export default {  6  data () {  7     return {  8  echarts,  9  echartsArr: [], 10  } 11  }, 12  watch: { 13  getOptions: { // 每次切換數據源,都須要從新渲染,因此用watch觀察數據是否改變 14  handler (newValue, oldValue) { 15         let chart = this.echartsArr[this.getCanvasId] 16         if (newValue) { 17           this.initChart(newValue) 18         } else { 19           this.initChart(oldValue) 20  } 21  }, 22       deep: true
23  } 24  }, 25  props: [ 26     'getOptions', 27     'getCanvasId'
28  ], 29  computed: {}, 30  methods: { 31  initChart (value) { 32       let _this = this
33       // wxLoading('加載中')
34       // this.clickFlag = false
35       setTimeout(() => { // 渲染須要延時執行,不要問爲何 36         // _this.$refs.echarts.clear()
37         _this.getOptions = value 38  _this.$refs.echarts.init() 39  wxHideLoading() 40       }, 200) 41 
42  }, 43 
44  handleInit(canvas, width, height) { 45       let chart = echarts.init(canvas, null, { 46  width: width, 47  height: height 48  }) 49  canvas.setChart(chart) 50  chart.clear() // 防止重複渲染,因此在構建以前,清空一下 51       chart.setOption(this.getOptions, true) // 從新構建數據源 52       this.echartsArr[this.getCanvasId] = chart 53       return chart 54  } 55  }, 56  components: { 57  mpvueEcharts 58  }, 59  onLoad () { 60  }, 61  onShow () { 62  }, 63  onHide () { 64  }, 65  onUnload () { 66  } 67 }

css文件沒什麼好說的api

而後在主頁面調用該組件echarts

 1 mpvue-echarts(:getOptions="wxOptions" :getCanvasId="canvasId") 

在control.js中調用選項卡切換方法ide

 1  /**  2  * 延時切換數據  3      */
 4  changeData(index) {  5       switch (index) {  6         case 0:  7           this.canvasId = 'line'
 8           this.wxOptions = this.ecDay  9           break
10         case 1: 11           this.canvasId = 'bar'
12           this.wxOptions = this.ec 13           break
14  } 15     },
相關文章
相關標籤/搜索