1.封装echarts
<template>
<div class="myCharts">
<div :id="uuid" :style="style" class="myChart"></div>
</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
interface Props {
height: string;
width: string;
options: any;
uuid: string;
}
const props = defineProps<Props>();
const myChart = ref<any>(null);
const style = computed(() => ({
height: props.height,
width: props.width
}));
watch(
[() => props.width, () => props.height, () => props.options],
([newWidth, newHeight, newOptions]) => {
console.log(newWidth, newHeight, newOptions);
if (myChart.value) {
try {
nextTick(() => {
myChart.value.resize({
animation: {
duration: 0 // 300ms 内完成尺寸变化
}
});
});
if (newOptions) {
myChart.value.setOption(newOptions, {
notMerge: true
});
}
} catch (error) {
console.error('Error occurred while resizing or setting options:', error);
}
}
},
{ deep: true }
);
onMounted(() => {
if (props.uuid) {
const chartDom = document.getElementById(props.uuid);
if (chartDom) {
myChart.value = markRaw(echarts.init(chartDom as HTMLElement));
if (props.options) {
myChart.value.setOption(props.options);
}
} else {
console.error(Element with id ${props.uuid} not found
);
}
}
onBeforeUnmount(() => {
if (myChart.value) {
myChart.value.dispose();
myChart.value = null;
}
});
</script>
<style scoped lang="less">
.myCharts {
width: 100%;
background: #fff;
padding: 20px;
border-radius: 6px;
.myChart {
margin-top: 10px;
height: 384px;
width: 100% !important;
}
}
</style>
2.使用
import EChartsComponent from '@/components/echarts/echarts.vue';
<EChartsComponent :uuid="'1'" :height="eachersHeaer" :width="eachersWidthr" :options="chartOptions" />
3.问题
会出现ts无法解析
需要在根目录配置echarts.d.ts
declare module 'echarts' {
export function init(...args: any[]): any;
// 添加其他需要的接口定义
}
在tsconfig.ts文件配置
"allowImportingTsExtensions": true,
"esModuleInterop": true,
"include": ["src//.ts", "src//.d.ts", "typings//.d.ts", "src//.tsx", "src//.vue", "./src/.d.ts"],