vue实现股市图
Vue 实现股市图
使用 ECharts 实现
ECharts 是一个强大的可视化库,支持绘制各种图表类型,包括 K 线图(蜡烛图)和折线图。在 Vue 项目中可以通过 vue-echarts 或直接引入 ECharts 实现。
安装依赖:
npm install echarts vue-echarts
引入并初始化图表:
<template>
<div>
<v-chart :option="chartOption" style="height: 400px;" />
</div>
</template>
<script>
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { CandlestickChart, LineChart } from "echarts/charts";
import {
GridComponent,
TooltipComponent,
TitleComponent,
DataZoomComponent,
} from "echarts/components";
import VChart from "vue-echarts";
use([
CanvasRenderer,
CandlestickChart,
LineChart,
GridComponent,
TooltipComponent,
TitleComponent,
DataZoomComponent,
]);
export default {
components: {
VChart,
},
data() {
return {
chartOption: {
title: {
text: "股票K线图",
},
tooltip: {
trigger: "axis",
},
grid: {
left: "10%",
right: "10%",
bottom: "15%",
},
xAxis: {
type: "category",
data: ["2023-01", "2023-02", "2023-03", "2023-04", "2023-05"],
},
yAxis: {
scale: true,
},
dataZoom: [
{
type: "inside",
start: 0,
end: 100,
},
{
start: 0,
end: 100,
},
],
series: [
{
type: "candlestick",
data: [
[20, 30, 10, 25],
[25, 35, 15, 30],
[30, 40, 20, 35],
[35, 45, 25, 40],
[40, 50, 30, 45],
],
},
],
},
};
},
};
</script>
使用 TradingVue.js
TradingVue.js 是一个专门为金融图表设计的 Vue 组件库,支持 K 线图、技术指标和实时更新。
安装依赖:
npm install trading-vue-js
基本用法:
<template>
<div>
<trading-vue :data="chartData" :width="width" :height="height" />
</div>
</template>
<script>
import TradingVue from "trading-vue-js";
export default {
components: {
TradingVue,
},
data() {
return {
width: 800,
height: 400,
chartData: {
ohlcv: [
[1551128400000, 33, 45.1, 30.13, 38.7, 24129],
[1551132000000, 38.7, 39.5, 36.5, 38.1, 23291],
[1551135600000, 38.1, 39.2, 37.8, 38.9, 20312],
],
},
};
},
};
</script>
使用 Lightweight Charts
Lightweight Charts 是 TradingView 推出的轻量级金融图表库,适合高频数据展示。
安装依赖:
npm install lightweight-charts
在 Vue 中使用:
<template>
<div ref="chartContainer" style="width: 800px; height: 400px;"></div>
</template>
<script>
import { createChart } from "lightweight-charts";
export default {
mounted() {
const chart = createChart(this.$refs.chartContainer, {
width: 800,
height: 400,
});
const candleSeries = chart.addCandlestickSeries();
candleSeries.setData([
{ time: "2023-01-01", open: 10, high: 15, low: 8, close: 12 },
{ time: "2023-01-02", open: 12, high: 16, low: 10, close: 14 },
]);
},
};
</script>
数据动态更新
对于实时数据,可以通过 WebSocket 或定时器动态更新图表数据:
methods: {
updateChart(newData) {
this.chartOption.series[0].data = newData;
// 如果是 TradingVue.js 或 Lightweight Charts,调用对应的更新方法
},
},
注意事项
- 确保数据格式符合图表库的要求,尤其是时间戳和价格数据。
- 高频数据更新时注意性能优化,避免频繁 DOM 操作。
- 移动端适配需调整图表尺寸和交互方式。







