小程序mpvue中动态切换echarts图表

时间:2023-03-09 16:37:57
小程序mpvue中动态切换echarts图表

如果你用mpvue,而且还想用echarts,那么这个包你可以以来一下

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

小程序mpvue中动态切换echarts图表

考虑到多个页面都休要用,所以抽出来作为一个组件,总得来说根据官方的例子小改动了一下

vue文件

 <template>
<div class="echarts-wrap">
<mpvue-echarts :echarts="echarts" :onInit="handleInit" canvasId="getCanvasId" ref="echarts" />
</div>
</template> <script src="./control.js"></script> <style scoped lang="stylus" src="./style.styl"></style>

js文件

 import echarts from 'echarts'
import mpvueEcharts from 'mpvue-echarts'
import { messageTip, wxHideLoading, wxLoading } from "../../utils/wxapi"; export default {
data () {
return {
echarts,
echartsArr: [],
}
},
watch: {
getOptions: { // 每次切换数据源,都需要重新渲染,所以用watch观察数据是否改变
handler (newValue, oldValue) {
let chart = this.echartsArr[this.getCanvasId]
if (newValue) {
this.initChart(newValue)
} else {
this.initChart(oldValue)
}
},
deep: true
}
},
props: [
'getOptions',
'getCanvasId'
],
computed: {},
methods: {
initChart (value) {
let _this = this
// wxLoading('加载中')
// this.clickFlag = false
setTimeout(() => { // 渲染需要延时执行,不要问为什么
// _this.$refs.echarts.clear()
_this.getOptions = value
_this.$refs.echarts.init()
wxHideLoading()
}, 200) }, handleInit(canvas, width, height) {
let chart = echarts.init(canvas, null, {
width: width,
height: height
})
canvas.setChart(chart)
chart.clear() // 防止重复渲染,所以在构建之前,清空一下
chart.setOption(this.getOptions, true) // 重新构建数据源
this.echartsArr[this.getCanvasId] = chart
return chart
}
},
components: {
mpvueEcharts
},
onLoad () {
},
onShow () {
},
onHide () {
},
onUnload () {
}
}

css文件没什么好说的

然后在主页面调用该组件

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

在control.js中调用选项卡切换方法

  /**
* 延时切换数据
*/
changeData(index) {
switch (index) {
case 0:
this.canvasId = 'line'
this.wxOptions = this.ecDay
break
case 1:
this.canvasId = 'bar'
this.wxOptions = this.ec
break
}
},