用于vue3的EchartsResize Hook函数
import { onMounted, onUnmounted, nextTick } from 'vue'
export function useEchartsResize(chartInstances) {
const debounce = (fn, delay) => {
let timer
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn()
}, delay)
}
}
const handleResize = () => {
nextTick(() => {
// 支持函数形式获取图表实例
const charts = typeof chartInstances === 'function' ? chartInstances() : chartInstances
if (Array.isArray(charts)) {
charts.forEach(it => {
const chart = typeof it === 'function' ? it() : it;
if (chart && typeof chart.resize === 'function') {
chart.resize()
}
})
} else if (charts && typeof charts.resize === 'function') {
charts.resize()
}
})
}
const debouncedResize = debounce(handleResize, 100)
onMounted(() => {
window.addEventListener('resize', debouncedResize)
})
onUnmounted(() => {
window.removeEventListener('resize', debouncedResize)
})
return {
handleResize: debouncedResize
}
}使用方式简单
import { useEchartsResize } from "./useEchartsResize";
const chart = shallowRef(null);
useEchartsResize(() => chart.value);图标自动变化大小
