1、mixins文件:resize.js
// 当调整浏览器窗口大小时,发生 resize 事件;监听resize,实现Echarts图表大小自适应浏览器窗口大小
export default {
data() {
return {
chart: null
}
},
mounted() {
window.addEventListener('resize', this.resize);
},
methods: {
resize() {
if (this.chart) {
this.chart.resize();
} else {
console.log('请重写resize方法');
}
},
},
beforeDestory() {
window.removeEventListener('resize', this.resize);
}
}
2、图表文件中混入resize.js
<template>
<div ref="barChart" class="chart-content">暂无数据</div>
</template>
<script>
import * as echarts from 'echarts';
import Resize from 'plugins/mixins/resize.js';
export default {
name: 'bar',
mixins: [Resize],
data() {
return {};
},
mounted() {
this.draw();
},
methods: {
draw() {
this.chart = echarts.init(this.$refs.barChart);
var option = {
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
},
yAxis: {
type: 'value',
},
series: [
{
name: '柱状',
type: 'bar',
data: [120, 200, 150, 80, 70, 110, 130],
showBackground: true,
backgroundStyle: {
color: 'rgba(255, 255, 0, 0.2)',
},
},
{
name: '折线',
type: 'line',
data: [140, 300, 160, 100, 80, 120, 190],
},
],
};
this.chart.setOption(option);
},
},
};
</script>
<style scoped>
.chart-content {
width: 100%;
height: 600px;
box-sizing: border-box;
border: 1px solid #ccc;
}
</style>
3、效果展示: