echarts实现宽高自适应
<template>
<div id="main" style="width:100%;height:300px;"></div>
</template>
<script>
export default {
data() {
return {
myChart: '',
isinit: false, // 是否已初始化过
screenWidth: document.body.clientWidth,
screenHeight: document.body.clientHeight,
}
},
methods: {
changeEcharts(){
if(!this.isinit){
var chartDom = document.getElementById('main');
this.myChart = this.$echarts.init(chartDom);
var option;
}
option = {
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'
}
]
};
option && this.myChart.setOption(option);
}
},
watch: {
// 监听窗口宽度变化时触发
screenWidth() {
this.isinit = true
// resize()重新绘制
this.myChart.resize()
},
// 监听窗口高度变化时触发
screenHeight(){
this.isinit = true
this.myChart.resize()
}
},
mounted() {
var that = this;
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth
that.screenWidth = window.screenWidth
window.screenHeight = document.body.clientHeight
that.screenHeight = window.screenHeight
})()
}
}
}
</script>
解决window.onresize失效
解决方法:将window.onresize换成window.addEventListener(‘resize’, () => {})
window.addEventListener('resize', () => {
window.screenWidth = document.body.clientWidth
that.screenWidth = window.screenWidth
window.screenHeight = document.body.clientHeight
that.screenHeight = window.screenHeight
})