<template>
<div class="trend-chart-container">
<div class="chart-content">
<div ref="chartRef"></div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch, computed } from "vue";
import * as echarts from "echarts";
const props = defineProps({
period: {
type: String,
default: "week",
},
});
const chartRef = ref(null);
const selectedPeriod = computed(() => props.period);
let chartInstance = null;
const periodData = {
week: {
xData: ["12.1", "12.2", "12.3", "12.4", "12.5", "12.6", "12.7"],
yData: [8, 12, 15, 10, 18, 14, 16],
},
month: {
xData: ["1日", "5日", "10日", "15日", "20日", "25日", "30日"],
yData: [45, 52, 48, 60, 55, 62, 58],
},
quarter: {
xData: ["1月", "2月", "3月"],
yData: [180, 220, 195],
},
};
const getChartOption = (period) => {
const data = periodData[period];
return {
grid: {
left: "10%", // 图表绘图区域距离容器左侧的距离(百分比)
right: "5%", // 图表绘图区域距离容器右侧的距离(百分比)
top: "20%", // 图表绘图区域距离容器顶部的距离(百分比)
bottom: "15%", // 图表绘图区域距离容器底部的距离(百分比)
},
xAxis: {
type: "category", // X 轴类型为类目轴(适用于离散数据)
data: data.xData, // X 轴的数据来源(横坐标标签)
boundaryGap: false, // 是否留白(false 表示数据点紧贴坐标轴)
axisLabel: {
color: "#ffffff", // X 轴标签文字颜色
},
axisLine: {
lineStyle: {
color: "#406080", // X 轴线条颜色
},
},
},
yAxis: {
type: "value", // Y 轴类型为数值轴(适用于连续数据)
min: 0, // Y 轴最小值
name: "单位:个", // Y 轴单位名称
nameLocation: "end", // 单位显示位置(end 表示在顶部)
nameGap: 20, // 单位与 Y 轴的距离
nameTextStyle: {
color: "#ffffff", // 单位文字颜色
fontSize: 14, // 单位文字大小
align: "center", // 单位文字对齐方式
},
axisLabel: {
color: "#ffffff", // Y 轴标签文字颜色
},
axisLine: {
lineStyle: {
color: "#406080", // Y 轴线条颜色
},
},
splitLine: {
lineStyle: {
color: "#305070", // Y 轴网格线颜色
},
},
},
series: [
{
name: "报警数量", // 系列名称(用于图例和提示框)
type: "line", // 图表类型为折线图
smooth: true, // 是否平滑曲线
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: "rgba(255, 41, 41, 0.8)" }, // 渐变起始颜色(顶部)
{ offset: 1, color: "rgba(255, 41, 41, 0.1)" }, // 渐变结束颜色(底部)
]),
},
lineStyle: {
color: "#ff2929", // 折线颜色
width: 2, // 折线宽度
},
itemStyle: {
color: "#ff2929", // 数据点颜色
},
data: data.yData, // Y 轴数据来源(纵坐标值)
},
],
};
};
onMounted(() => {
chartInstance = echarts.init(chartRef.value);
chartInstance.setOption(getChartOption(selectedPeriod.value));
chartInstance.resize();
});
watch(selectedPeriod, (newPeriod) => {
if (chartInstance) {
chartInstance.setOption(getChartOption(newPeriod), { notMerge: true });
}
});
</script>
<style scoped>
.trend-chart-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.chart-content {
flex: 1;
display: flex;
flex-direction: column;
}
.chart-content > div {
width: 100%;
height: 100%;
}
</style>

效果如上




