| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <template>
- <div ref="chartDom" class="line-chart"></div>
- </template>
- <script setup>
- import { onMounted, ref, watch } from "vue";
- import * as echarts from "echarts";
- import { barOption } from "./chartOption.js";
- import { deepClone } from "@/common/commonFun";
- const props = defineProps({
- chartData: {
- type: Object,
- default: () => ({
- categories: [],
- values: [],
- }),
- },
- yAxisFormatter: {
- type: String,
- default: "{value}%", // 默认百分比格式
- },
- });
- const chartDom = ref(null);
- let myChart = null;
- const initData = () => {
- const newOption = deepClone(barOption);
-
- // 如果有传入数据,使用传入的数据
- if (props.chartData && props.chartData.categories && props.chartData.categories.length > 0) {
- newOption.xAxis.data = props.chartData.categories;
- newOption.series[0].data = props.chartData.values;
- }
-
- // 更新 yAxis 的 formatter
- newOption.yAxis.axisLabel.formatter = props.yAxisFormatter;
-
- myChart.setOption(newOption);
- };
- // 监听数据变化,更新图表
- watch(
- () => [props.chartData, props.yAxisFormatter],
- () => {
- if (myChart) {
- initData();
- }
- },
- { deep: true }
- );
- onMounted(() => {
- myChart = echarts.init(chartDom.value);
- initData();
- });
- </script>
- <style lang="scss" scoped>
- .line-chart {
- width: 100%;
- height: 100%;
- }
- </style>
|