小程序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
}
},
watch: {
getOptions: { // 每次切换数据源,都需要重新渲染,所以用watch观察数据是否改变
handler (newValue, oldValue) {
if (newValue) {
this.initChart(newValue)
} else {
this.initChart(oldValue)
}
},
deep: true
}
},
props: [
'getOptions',
'getCanvasId'
],
computed: {},
methods: {
initChart (value) {
let _this = this
setTimeout(() => { // 渲染需要延时执行,不要问为什么
_this.getOptions = value
echarts.dispose(_this.$refs.echarts); // 处理内存泄漏
_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样式
我这里设置的图标高度是300
.echarts-wrap
width: 100vw;
height: 300px;
在页面中使用
导入echarts组件
import mpEcharts from '../../components/mpvue_echarts'
export default {
data () {
return {
wxOptions: this.ecDay,
ecDay: {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
},
ecMonth: {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(220, 220, 220, 0.8)'
}
}]
}
}
},
computed: {},
methods: {
/**
* 延时切换数据
*/
changeData(index) {
switch (index) {
case 0:
this.canvasId = 'line'
this.wxOptions = this.ecDay
break
case 1:
this.canvasId = 'bar'
this.wxOptions = this.ecMonth
break
}
},
},
components: {
mpvueEcharts
},
onLoad () {
},
onShow () {
},
onHide () {
},
onUnload () {
}
}
在vue文件中使用
<template>
<div class="echarts-wrap">
<span @click="changeData(0)">切换数据源0</span>
<span @click="changeData(1)">切换数据源1</span>
<mp-echarts :getOptions="wxOptions" :getCanvasId="canvasId"></mp-echarts>
</div>
</template>
<script src="./control.js"></script>
<style scoped lang="stylus" src="./style.styl"></style>