<template>
<div
ref="chartDom"
:class="className"
:style="{height:height, width:width}"
></div>
</template>
<script>
import { useDebounceFn } from "@vueuse/core";
import echarts from "echarts";
import { onMounted, onUnmounted, ref, watch, nextTick } from "vue";
export default {
// echarts dom class名称
name: "VEcharts",
props: {
className: {
type: String,
default: "chart",
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "100%",
},
loading: {
type: [Boolean, Number],
default: false,
},
// charts配置项
option: {
type: Object,
required: true,
},
// 主题
model: {
type: String,
default: "chalk",
},
},
setup(props, content) {
const chartDom = ref(null);
let chart = null;
const resizeHandler = useDebounceFn(() => {
if (chart) {
setTimeout(() => {
chart.resize();
}, 100);
}
}, 100);
onMounted(() => {
setTimeout(() => {
nextTick(() => {
window.dispatchEvent(new Event("resize"));
});
}, 3000);
chart = echarts.init(chartDom.value);
chart.setOption(props.option);
content.emit("update:echartref", chart);
window.addEventListener("resize", resizeHandler);
});
// 通过 loading 状态判断 刷新渲染时机
watch(
() => props.loading,
(loading) => {
if (loading === true) return;
if (typeof loading === "number" && loading <= 0) return;
setOptionDebounce();
}
);
const setOptionDebounce = useDebounceFn(() => {
chart.resize();
chart.setOption(props.option);
}, 500);
onUnmounted(() => {
if (!chart) return;
window.removeEventListener("resize", resizeHandler);
chart.dispose();
chart = null;
});
return {
chartDom,
};
},
};
// 父组件引用:
// <VEcharts width='100px' height='100' loading='loading' option='option'></VEcharts>
</script>
vue3.0中echarts初始化
最新推荐文章于 2024-05-20 15:17:08 发布