🤞Ecarts在Vue中使用父子组件异步传值🤞
🛴:注意采用的异步传值
npm install echarts
我是分为echarts.js 和 MyEchart.vue 两个文件,也可以把这两个文件合为一个
echarts.js
import * as echarts from 'echarts/core'
/**
引入需要的图表,需要什么就加什么
*/
import { BarChart, LineChart, PieChart } from 'echarts/charts'
// 引入提示框,标题,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
LegendComponent,
ToolboxComponent
} from 'echarts/components'
// 标签自动布局,全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features'
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers'
// 注册必须的组件,上面引入的都需要在此注册
echarts.use([
ToolboxComponent,
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
LabelLayout,
UniversalTransition,
CanvasRenderer,
BarChart,
LineChart,
PieChart
])
// 导出
export default echarts
MyEchart.vue
(注意里边的注释,采用异步更新值来更新,防止父子组件数据不同步)
<template>
<div ref="chartRef" class="my-chart"></div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref,watch } from "vue";
import echarts from "./echarts";
const props = defineProps(["options"]);
const chartRef = ref<HTMLDivElement>();
let chart: echarts.ECharts | null = null;
const resizeHandler = () => {
chart?.resize(); //重新调整图表的大小和布局,以适应容器的变化
//?. 是可选链操作符,用于在 chart 对象存在时才执行后面的方法调用。如果 chart 对象为 null 或 undefined,则不会调用 resize 方法,避免出现错误。
};
onMounted(() => {
setTimeout(() => {
initChart();
}, 20); //这个值设置的太小容易其他组件数据还没获取到,这边就加载了,还有另一部异步监听加载值,下边的watch代码
window.addEventListener("resize", resizeHandler);
});
const initChart = () => {
chart = echarts.init(chartRef.value as HTMLDivElement); //开启深色模式
chart.setOption({
...props.options,
});
};
onBeforeUnmount(() => {
window.removeEventListener("resize", resizeHandler);
chart?.dispose();
});
watch(props.options, async (newVal, oldVal) => {
chart.setOption({ //异步传值,如果子组件渲染完,但是父组件还没有传递过来值,所以需要监听异步渲染
...props.options,
});
})
</script>
<style lang="scss" scoped></style>
<template>
<div>
<MyEchart :options="options" style="height: 300px"/>
</div>
</template>
<script setup name="Index">
import MyEchart from "@/components/Echarts/MyEchart"
const options = reactive({
title: {
text: 'ShareIt统计'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['Email']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {},
// 可以添加其他工具按钮...
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1','2','3','4','5','6','7']
},
yAxis: {
type: 'value'
},
series: [
{
name: 'Email',
type: 'line',
stack: 'Total',
data: [120, 132, 101, 134, 90, 230, 210]
}
]
})
function updateOptions(){
// 根据需求自行更新options....
}
</script>
大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。