Echarts 图表自适应屏幕

使用 setTimeout 进行屏幕自适应

<template>
	<div ref="charts" style="width:100%;height:440px"></div>
</template>
import {ref,onMounted} from 'vue'
import * as echarts from 'echarts'

const charts = ref()
let echartInstance ;
onMounted(()=>{
	echartInstance = echarts.init(charts.value,'macarons');
	setTimeout(()=>{
		echartInstance.resize();
	},100);
})

使用 window.onresize 进行屏幕自适应(建议使用)

<template>
	<div ref="charts" style="width:100%;height:440px"></div>
</template>
import {ref,onMounted} from 'vue'
import * as echarts from 'echarts'

const charts = ref()
let echartInstance ;
onMounted(()=>{
	echartInstance = echarts.init(charts.value,'macarons');
	window.onresize = function(){
		echartInstance.resize();
	};
})

使用resize()方法

  • mixins / resize.ts
import {getCurrentInstance,onBeforeUnmount,onMounted} from 'vue'

export default function(){
	let proxy;
	onMounted(()=>{
		proxy = getCurrentInstance();
		window.addEventListener('resize',resize);
	});
	onBeforeUnmount(()=>{
		window.removeEventLinstener('resize',resize);
	})
	function resize(){
		proxy.exposed.resize();
	}
	
}
  • useEcharts.vue
import useResize from './mixins/resize'

function resize(){
	echartInstance.resize();
}
defineExpose({resize});
useResize();