文章目录
在低代码、可视化热潮的推动下,越来越多的前端项目希望实现“通过配置 JSON 自动生成图表大屏”的能力。本项目基于 Vue 3 和 ECharts 实现一个数据可视化大屏编辑器,支持用户通过 JSON 结构快速构建并渲染复杂图表界面,极大降低图表搭建成本。
一、核心思路概览
1. 数据结构设计
我们将可视化大屏拆解为以下两部分配置:
- layout:图表在大屏中的位置与大小(结合
vue-grid-layout实现自由拖拽) - charts:图表的类型、标题、绑定数据等核心信息
示例配置结构如下:
{
"layout": [
{
"i": "chart1", "x": 0, "y": 0, "w": 6, "h": 4 },
{
"i": "chart2", "x": 6, "y": 0, "w": 6, "h": 4 }
],
"charts": [
{
"id": "chart1",
"type": "bar",
"title": "销售额柱状图",
"data": {
"x": ["Q1", "Q2", "Q3", "Q4"],
"y": [120, 200, 150, 80]
}
},
{
"id": "chart2",
"type": "line",
"title": "趋势折线图",
"data": {
"x": ["Jan", "Feb", "Mar", "Apr"],
"y": [30, 50, 45, 60]
}
}
]
}
二、组件结构拆解
我们将整个项目拆分为如下几个核心组件:
ChartRenderer.vue:图表渲染器,负责渲染不同类型的 ECharts 图表LayoutGrid.vue:基于vue-grid-layout实现的大屏布局容器ScreenEditor.vue:主页面,载入 JSON 配置 → 渲染布局和图表
三、核心组件代码示例
1. ChartRenderer.vue
<template>
<div ref="chartRef" class="chart-container"></div>
</template>
<script setup>
import {
onMounted, watch, ref } from 'vue'
import * as echarts from 'echarts'
const props = defineProps({
chart: Object
})
const chartRef = ref()
watch(
() => props.chart,
() => {
renderChart()
},
{
immediate: true }
)
function renderChart() {
if (!chartRef.value) return
const chartInstance = echarts.init(chartRef.value)
const {
type, data, title } = props.chart
const option = {
title: {
text: title },</

最低0.47元/天 解锁文章
6794

被折叠的 条评论
为什么被折叠?



