vue实现折线图
使用 ECharts 实现折线图
安装 ECharts 依赖
npm install echarts --save
在 Vue 组件中引入 ECharts
import * as echarts from 'echarts'
创建图表容器
<template>
<div id="lineChart" style="width: 600px; height: 400px;"></div>
</template>
初始化图表

mounted() {
this.initLineChart()
},
methods: {
initLineChart() {
const chartDom = document.getElementById('lineChart')
const myChart = echarts.init(chartDom)
const option = {
title: {
text: '折线图示例'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['销量']
},
xAxis: {
type: 'category',
data: ['1月', '2月', '3月', '4月', '5月', '6月']
},
yAxis: {
type: 'value'
},
series: [
{
name: '销量',
type: 'line',
data: [150, 230, 224, 218, 135, 147]
}
]
}
myChart.setOption(option)
}
}
使用 Vue-ECharts 封装组件
安装 vue-echarts
npm install vue-echarts echarts --save
创建可复用组件

<template>
<v-chart :option="chartOption" autoresize />
</template>
<script>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
LegendComponent,
GridComponent
])
export default {
components: { VChart },
data() {
return {
chartOption: {
// 同上示例的option配置
}
}
}
}
</script>
响应式数据更新
动态更新图表数据
watch: {
chartData(newVal) {
if (this.myChart) {
this.myChart.setOption({
series: [{
data: newVal
}]
})
}
}
}
图表自适应
添加窗口大小变化监听
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
if (this.myChart) {
this.myChart.resize()
}
}
}
自定义主题样式
创建自定义主题
const myTheme = {
color: ['#c23531', '#2f4554', '#61a0a8'],
backgroundColor: '#f5f5f5'
}
// 注册主题
echarts.registerTheme('myTheme', myTheme)
// 使用主题
echarts.init(chartDom, 'myTheme')






