vue2:
- mixin混入
- extends继承js
// BaseCom.js
<script>
export default {
data(){
return{
myCharts:null,
option:{}
}
},
mounted() {
initEcharts();
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeFn, false);
},
methods: {
initEcharts(){
this.myCharts = echarts.init(ele);
if (this.option) {
this.myCharts.setOption(this.option);
}
// 如果因为增加Transition等过渡动画导致echarts初始化对容器宽高计算不准确,可以如下延时调用
// 时间需要大于过渡动画时间(过渡动画时间可以配置,具体参考官网Transition),确保在动画完成后即可
setTimeout(resizeFn, 50);
window.addEventListener('resize', useThrottleFn(resizeFn, 50), false);
},
resizeFn = () => {
this.myCharts.resize();
}
},
}
</script>
// extendCom
import BaseCom from './BaseCom.js'
export default {
extends: BaseCom,
}
vue3: 一般是封装hook,在每一个echarts组件中调用
// useEcharts.ts
import type { Ref } from 'vue';
import * as echarts from 'echarts';
import { useThrottleFn } from '@vueuse/core';
import type { EChartsType, EChartsCoreOption } from 'echarts';
export default function useEcharts(ele: Ref<HTMLElement>, option?: EChartsCoreOption) {
const myCharts = shallowRef<EChartsType>();
onBeforeUnmount(() => {
window.removeEventListener('resize', resizeFn, false);
});
// initEcharts也可以放在watchEffect中调用,而不使用onMounted
// const stop = watchEffect(() => {initEcharts();},{ flush: 'post' });
onMounted(()={
initEcharts();
})
const initEcharts = () => {
if (ele.value) {
myCharts.value = echarts.init(ele.value);
if (option) {
myCharts.value?.setOption(option);
}
// 如果因为增加Transition等过渡动画导致echarts初始化对容器宽高计算不准确,可以如下延时调用
// 时间需要大于过渡动画时间(过渡动画时间可以配置,具体参考官网Transition),确保在动画完成后即可
setTimeout(resizeFn, 50);
window.addEventListener('resize', useThrottleFn(resizeFn, 50), false);
//stop();
}
};
const resizeFn = () => {
myCharts.value?.resize();
};
// 返回echarts示例,需要时可以在组件中使用
return myCharts;
}
// component.vue
<template>
<div class="wrapper" ref="echartsRef"></div>
</template>
<script setup lang="ts">
import useEcharts from '@/hook/useEcharts';
const option = reactive({
// echarts option 略
});
const echartsRef = shallowRef();//此处使用shallowRef,使用ref在某些情况下会报错
useEcharts(echartsRef, option);
</script>