首先我们去封装一个Hooks
- 为啥要封装Hooks
在vue2中我们可以全局导入echarts 通过this. e c a h r t s 方式去使用 e c h a t s , 在 v u e 3 中使用了组合式 A p i 对于 t h i s 的支持不是方便所以为了便于开发建议自己去封装 h o o k s 来代替 t h i s . ecahrts方式去使用echats,在vue3中使用了组合式Api对于this的支持不是方便 所以为了便于开发建议自己去封装hooks来代替this. ecahrts方式去使用echats,在vue3中使用了组合式Api对于this的支持不是方便所以为了便于开发建议自己去封装hooks来代替this.ecahrts
Hoos的封装
import * as echarts from "echarts";
import type { Ref } from "vue";
import { onUnmounted } from "vue";
type EchartsInstance = echarts.ECharts
export default function useEcharts(divEl: HTMLDivElement) {
console.log(divEl)
const echartsInstance: EchartsInstance = echarts.init(divEl, null, { renderer: "svg" });
onUnmounted(() => {
echartsInstance.dispose();
});
function setOption(option: echarts.EChartsOption) {
echartsInstance.setOption(option);
}
function resizeEcharts() {
echartsInstance.resize();
}
return {
echartsInstance,
setOption,
resizeEcharts,
};
}
(可能封装的不是太好 你也可以进行优化 添加更多的功能)
食用方法(以官网折线图为例)
<template>
<div class="">
<div ref="Wrapper" id="cahrtsDom"></div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import useEcharts from '../Hooks/UserEcharts'
let wfChart: any = null;
const Wrapper = ref();
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
onMounted(() => {
setupEcharts()
})
function setupEcharts() {
if (!wfChart) {
wfChart = useEcharts(Wrapper.value);
}
wfChart.setOption(option);
}
</script>
<style scoped>
#cahrtsDom {
width: 400px;
height: 400px;
}
</style>
如果不使用ts开发呢 你可以用这个Js版本Hooks
// 对userEcharts进行封装 封装的好处在于我们后期可以对我们的图像进行统一的管理
import * as echarts from "echarts";
import { onUnmounted } from "vue";
export default function useEcharts(divEl) {
// 谁要使用Echarts图表就把挂载点传递过来
// 初始化画布 挂载点 背景颜色 渲染器
const echartsinStance = echarts.init(divEl, null, { renderer: "svg" });
onUnmounted(() => {
// 在组件销毁的时候我们把EEcharts实例释放掉
echartsinStance.dispose();
});
function setOption(option) {
echartsinStance.setOption(option);
}
function ressizeEcharts() {
echartsinStance.resize();
}
return {
echartsinStance,
setOption,
ressizeEcharts,
};
}