vue实现走势图
使用 Vue 实现走势图
安装依赖
需要安装 echarts 或 chart.js 等图表库。以 echarts 为例:
npm install echarts vue-echarts
基础实现
在 Vue 组件中引入 ECharts 并初始化走势图:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chart = echarts.init(this.$refs.chart);
const option = {
title: { text: '走势图示例' },
tooltip: {},
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: { type: 'value' },
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
};
chart.setOption(option);
}
}
};
</script>
动态数据更新
通过 watch 或方法调用实现数据动态更新:
methods: {
updateData(newData) {
const chart = echarts.getInstanceByDom(this.$refs.chart);
chart.setOption({
series: [{ data: newData }]
});
}
}
响应式调整
监听窗口变化并调整图表大小:
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
const chart = echarts.getInstanceByDom(this.$refs.chart);
chart.resize();
}
}
使用 Vue-ECharts 封装
若需更简洁的封装,可使用 vue-echarts:
<template>
<v-chart :option="option" style="width: 100%; height: 400px;" />
</template>
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
use([
CanvasRenderer,
LineChart,
TitleComponent,
TooltipComponent,
GridComponent
]);
export default {
components: { VChart },
data() {
return {
option: {
title: { text: '封装后的走势图' },
xAxis: { data: ['A', 'B', 'C', 'D'] },
yAxis: {},
series: [{ type: 'line', data: [10, 22, 28, 43] }]
}
};
}
};
</script>
自定义样式与交互
通过 ECharts 配置实现高级功能:
- 区域高亮:添加
visualMap组件。 - 标记点:在
series中配置markPoint。 - 主题切换:使用
echarts.registerTheme注册自定义主题。
示例配置片段:
option: {
visualMap: {
show: false,
pieces: [{ gt: 1000, color: 'red' }]
},
series: [{
markPoint: {
data: [{ type: 'max', name: '最大值' }]
}
}]
}






