You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

165 lines
3.2 KiB

<template>
<div ref="chartContainer" class="line-chart-container"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
// 定义组件属性
interface Props {
chartData?: Array<{ name: string; value: number }>
title?: string
color?: string
}
const props = withDefaults(defineProps<Props>(), {
chartData: () => [],
title: '',
color: '#1296db'
})
// 图表容器引用和实例
const chartContainer = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null
// 初始化图表
const initChart = () => {
if (chartContainer.value) {
chartInstance = echarts.init(chartContainer.value)
updateChart()
}
}
// 更新图表
const updateChart = () => {
if (!chartInstance || !props.chartData.length) return
const option = {
title: {
text: props.title,
textStyle: {
color: '#fff',
fontSize: 14
},
left: 'center'
},
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0, 0, 0, 0.7)',
borderColor: 'rgba(30, 120, 255, 0.4)',
borderWidth: 1,
textStyle: {
color: '#fff'
}
},
xAxis: {
type: 'category',
data: props.chartData.map(item => item.name),
axisLine: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.3)'
}
},
axisLabel: {
color: 'rgba(255, 255, 255, 0.7)'
}
},
yAxis: {
type: 'value',
axisLine: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.3)'
}
},
splitLine: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.1)'
}
},
axisLabel: {
color: 'rgba(255, 255, 255, 0.7)'
}
},
series: [
{
data: props.chartData.map(item => item.value),
type: 'line',
smooth: true,
showSymbol: false,
lineStyle: {
color: props.color,
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: props.color + '80' // 添加透明度
},
{
offset: 1,
color: props.color + '00' // 透明
}
]
}
}
}
],
grid: {
left: '5%',
right: '5%',
top: '15%',
bottom: '10%',
containLabel: true
}
}
chartInstance.setOption(option)
}
// 监听数据变化
watch(
() => props.chartData,
() => {
updateChart()
},
{ deep: true }
)
// 窗口大小改变时重绘图表
const handleResize = () => {
if (chartInstance) {
chartInstance.resize()
}
}
// 组件挂载时初始化图表
onMounted(() => {
initChart()
window.addEventListener('resize', handleResize)
})
// 组件销毁前清理资源
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize)
if (chartInstance) {
chartInstance.dispose()
chartInstance = null
}
})
</script>
<style scoped>
.line-chart-container {
width: 100%;
height: 100%;
min-height: 200px;
}
</style>