Vue中使用Echarts绘图,DOM改变后重绘
1. 我的项目背景
首先,我使用Vue
+Element-UI
搭建的系统框架,左侧菜单栏和标题,右侧上方横条上有一个按钮,点击可以实现菜单栏的折叠与展开。
2. Echarts图表不能重绘
一开始的思路,是监听DOM变化,于是在网上搜索了一些方法,但是由于本系统并不会大量地改变DOM,没有必要监听DOM宽高的变化。系统中只有折叠和展开两个状态,所以只需要简单的用一个flag
表示,监听其true
/false
就可以了。我通过在store
中创建变量isCollapse
来管理折叠与展开。
store
代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
isCollapse: false
},
mutations: {
commitCollapse(state, bool) {
state.isCollapse = bool;
}
}
})
3. 监听isCollapse
变化,调用echarts
的resize
API
我们在绘制echarts的vue单文件中监听isCollapse
变化,然后调用resize就可以了。
<template>
<div :id="chartId" style="height: 100%;width: 100%;"></div>
</template>
<script>
var echarts = require("echarts");
export default {
data() {
return {
chartId: "pie",
myChart: null,
option: {
// 你的option
}
}
},
/* *******************重点******************** */
computed:{
isCollapse(){
return this.$store.state.isCollapse;
}
},
watch:{
isCollapse(newValue, oldValue){
this.myChart.resize();
}
},
/* ******************************************* */
mounted() {
// 基于准备好的dom,初始化echarts实例
this.myChart = echarts.init(document.getElementById(this.chartId));
this.myChart.setOption(this.option);
}
};
</script>