Vue3 使用 Script Setup 和 ECharts 实现动态电测听体检报告单图表
<template>
<div>
<button @click="openModal">打开弹窗</button>
<div ref="chartContainer" style="width: 600px; height: 400px;"></div>
</div>
</template>
<script setup>
import { onMounted, reactive, watch } from 'vue';
import * as echarts from 'echarts';
const chartData = reactive({
leftEar: [],
rightEar: [],
});
const chartInstance = echarts.init($refs.chartContainer);
let isModalOpen = false;
onMounted(() => {
// 监听弹窗打开事件
watch(() => isModalOpen, (isOpen) => {
if (isOpen) {
// 初始化图表配置
const options = {
xAxis: {
type: 'category',
data: [],
},
yAxis: {
type: 'value',
},
series: [
{
type: 'line',
symbol: 'none',
data: chartData.leftEar,
},
{
type: 'line',
symbol: 'circle',
data: chartData.rightEar,
},
],
};
// 设置图表配置
chartInstance.setOption(options);
}
});
// 监听表单数据变化,并更新图表数据
watch(() => chartData.leftEar, () => {
const options = {
series: [
{
data: chartData.leftEar,
},
],
};
chartInstance.setOption(options);
});
watch(() => chartData.rightEar, () => {
const options = {
series: [
{
data: chartData.rightEar,
},
],
};
chartInstance.setOption(options);
});
// 监听弹窗关闭事件,销毁图表实例
watch(() => isModalOpen, (isOpen) => {
if (!isOpen) {
chartInstance.dispose();
}
});
});
function openModal() {
isModalOpen = true;
// 打开弹窗逻辑
}
</script>
原文地址: https://www.cveoy.top/t/topic/p3s4 著作权归作者所有。请勿转载和采集!