vue实现四象限
Vue 实现四象限图的方法
使用 Vue 实现四象限图可以通过集成图表库(如 ECharts 或 Chart.js)或基于 SVG/Canvas 自定义绘制。以下是两种常用方法:
使用 ECharts 实现
ECharts 支持散点图(scatter)的定制化展示,适合四象限场景。安装 ECharts 后,通过配置坐标轴和系列数据实现:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
const chart = echarts.init(this.$refs.chart);
chart.setOption({
xAxis: {
type: 'value',
axisLabel: { formatter: '{value}' },
splitLine: { lineStyle: { type: 'dashed' } }
},
yAxis: {
type: 'value',
axisLabel: { formatter: '{value}' },
splitLine: { lineStyle: { type: 'dashed' } }
},
series: [{
type: 'scatter',
data: [
[10, 20], [-10, 20], [-10, -20], [10, -20]
],
symbolSize: 20,
label: {
show: true,
formatter: (params) => ['第一象限', '第二象限', '第三象限', '第四象限'][params.dataIndex]
}
}]
});
}
};
</script>
关键点:
- 通过
xAxis和yAxis定义坐标轴。 - 数据点
data的坐标决定象限位置。 splitLine的虚线样式增强象限分隔效果。
使用 SVG 自定义绘制
通过 Vue 的模板直接渲染 SVG 元素,动态计算坐标和标签位置:
<template>
<svg width="400" height="400" viewBox="-200 -200 400 400">
<!-- 坐标轴 -->
<line x1="-200" y1="0" x2="200" y2="0" stroke="black" />
<line x1="0" y1="-200" x2="0" y2="200" stroke="black" />
<!-- 象限标签 -->
<text x="50" y="-50" fill="blue">第一象限</text>
<text x="-100" y="-50" fill="green">第二象限</text>
<text x="-100" y="50" fill="red">第三象限</text>
<text x="50" y="50" fill="purple">第四象限</text>
<!-- 示例数据点 -->
<circle cx="50" cy="-50" r="5" fill="blue" />
<circle cx="-50" cy="-50" r="5" fill="green" />
<circle cx="-50" cy="50" r="5" fill="red" />
<circle cx="50" cy="50" r="5" fill="purple" />
</svg>
</template>
关键点:
- SVG 的坐标系原点
(0,0)位于中心。 - 通过
viewBox定义画布范围,支持响应式缩放。 - 使用
<text>和<circle>分别绘制标签和数据点。
动态数据绑定
结合 Vue 的响应式特性,动态更新象限数据:
<template>
<div>
<button @click="addData">添加数据</button>
<svg width="400" height="400" viewBox="-200 -200 400 400">
<line x1="-200" y1="0" x2="200" y2="0" stroke="black" />
<line x1="0" y1="-200" x2="0" y2="200" stroke="black" />
<circle v-for="(point, index) in points" :key="index"
:cx="point.x" :cy="-point.y" r="5" :fill="colors[index % 4]" />
</svg>
</div>
</template>
<script>
export default {
data() {
return {
points: [{ x: 30, y: 30 }, { x: -30, y: 30 }],
colors: ['blue', 'green', 'red', 'purple']
};
},
methods: {
addData() {
this.points.push({
x: Math.random() * 100 - 50,
y: Math.random() * 100 - 50
});
}
}
};
</script>
关键点:
v-for动态渲染数据点。- 点击事件触发数据更新,视图自动响应。
注意事项
- 交互扩展:可结合 Vue 的
@click事件实现数据点交互。 - 响应式设计:使用 CSS 或 JavaScript 监听容器尺寸变化,动态调整图表大小。
- 性能优化:大数据量时考虑虚拟滚动或 WebGL 渲染(如 ECharts GL)。







