vue中echarts3.0自适应的方法
前端时间做一个vue的项目,echart是按需引入的如下:
//引入ECharts主模块 importechartsfrom'echarts/lib/echarts' //引入折线图 import'echarts/lib/chart/line' //引入提示框和图例组件 import'echarts/lib/component/tooltip' import'echarts/lib/component/legendScroll'
然后发现在缩放浏览器窗口时折线图并不会自适应,费了好一会才解决,记录下来给需要的小伙伴,
第一种:浏览器自适应
通过:
在myChart.setOption后添加
window.onresize=myChart.resize;
如果有多个图形,可以封装成方法:
mounted(){
this.changEcharts();
},
methods:{
changEcharts(){
window.addEventListener('resize',()=>{
this.drawLineDom.resize();
this.todayFlowDom.resize();
this.hitRateDom.resize();});};},}
this.drawLineDom=this.$echarts.init(document.getElementById('chart-bandwidth'));
第二种情况,根据div大小的变化进行自适应
因为vue不能实时监测div大小变化的,所以我定义了一个按键,当按键的值变化的时候,进行resize;
import{mapState}from'vuex';
computed:mapState({isCollapse:'isCollapse',//这里我是语用的vuex保存的变量,可以不用vuex,我是因为组件之间的通讯}),
watch:{
isCollapse(){//注意一定不要用箭头函数,会获取不到this
setTimeout(()=>{
this.drawLineDom.resize();
this.todayFlowDom.resize();
this.hitRateDom.resize();
},500);},},
其实我用这个是在导航进行伸缩的时候,导致div大小发生了变化,所以这样执行reszie,就能完美的自适应
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。