Json 组件
组件概述
Json 组件库提供了处理 JSON 数据的通用解决方案,包含三个子组件:
- JsonPopover: JSON 数据预览组件,提供友好的悬停预览和完整的 JSON 查看功能
- JsonScheme: 核心动态表单组件,支持根据字段配置动态生成表单
- JsonSchemeForm: 表单包装组件,用于 BasicForm 集成
组件目录
src/components/Json/
├── JsonPopover.vue # JSON 预览组件
├── JsonScheme.vue # 动态表单核心组件
├── JsonSchemeForm.vue # 表单包装组件
├── types.ts # TypeScript 类型定义
└── index.ts # 组件导出1. JsonPopover 组件
功能特性
| 特性 | 说明 |
|---|---|
| 悬停预览 | 鼠标悬停时显示 Popover 查看完整 JSON |
| 双视图模式 | 友好展示模式(表格) / 原始数据模式(JSON 代码) |
| 语法高亮 | 类似 VS Code 的深色主题语法高亮 |
| 一键复制 | 支持一键复制 JSON 到剪贴板 |
| 字段摘要 | 显示配置项数量统计 |
| 友好名称 | 支持字段标签映射显示 |
Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| json | JSON 数据(对象或字符串) | Record<string, any> | string | null | - |
| title | Popover 标题 | string | 'JSON 配置' |
| alwaysShow | 是否始终显示 Popover(不悬停) | boolean | false |
| previewLength | 预览文本的最大长度 | number | 50 |
| showSummary | 是否显示字段数量摘要 | boolean | true |
| maxHeight | 最大高度 | string | '400px' |
| maxWidth | 最大宽度 | string | '600px' |
| jsonFields | 字段定义配置(用于显示友好名称) | any[] | [] |
TypeScript 类型定义
interface JsonPopoverProps {
json?: Record<string, any> | string | null;
title?: string;
alwaysShow?: boolean;
previewLength?: number;
showSummary?: boolean;
maxHeight?: string;
maxWidth?: string;
jsonFields?: JsonField[];
}使用示例
在表格列定义中使用
// CdpGrade.data.ts
import { BasicColumn } from '@/components/Table';
import { h } from 'vue';
import { JsonPopover } from '@/components/Json';
export const columns: BasicColumn[] = [
{
title: '等级配置',
align: 'center',
dataIndex: 'settingConfig',
width: 200,
customRender: ({ record }) => {
return h(JsonPopover, {
json: record.settingConfig,
title: '等级配置',
});
},
},
];在 .vue 文件中使用
<template>
<JsonPopover
:json="jsonData"
title="配置详情"
:jsonFields="jsonFields"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { JsonPopover } from '@/components/Json';
const jsonData = ref({
bgimg: 'http://example.com/image.png',
upgradeThreshold: 1000,
discountRate: 95,
freeShipping: true
});
const jsonFields = ref([
{ key: 'bgimg', label: '背景图', description: '等级背景图片' },
{ key: 'upgradeThreshold', label: '升级阈值', description: '升级所需积分' },
{ key: 'discountRate', label: '折扣率', description: '会员折扣百分比' },
{ key: 'freeShipping', label: '包邮', description: '是否免运费' }
]);
</script>视图模式
友好展示模式(默认)
以表格形式展示 JSON 数据,显示字段标签、值和说明:
| 字段 | 值 | 说明 |
|---|---|---|
| 背景图 (bgimg) | [对象] | 等级背景图片 |
| 升级阈值 (upgradeThreshold) | 1000 | 升级所需积分 |
| 折扣率 (discountRate) | 95 | 会员折扣百分比 |
| 包邮 | 是 (绿色) | 是否免运费 |
原始数据模式
以 JSON 代码形式展示,带语法高亮:
{
"bgimg": "http://example.com/image.png",
"upgradeThreshold": 1000,
"discountRate": 95,
"freeShipping": true
}语法高亮颜色
| JSON 类型 | 颜色 | 色值 |
|---|---|---|
| 键名 | 红色 | #e06c75 |
| 字符串 | 绿色 | #98c379 |
| 数字 | 橙色 | #d19a66 |
| 布尔值 | 蓝色 | #56b6c2 |
| null | 紫色 | #c678dd |
2. JsonScheme 组件
功能特性
| 特性 | 说明 |
|---|---|
| 动态表单 | 根据 JsonField 配置动态生成表单 |
| 多种字段类型 | 支持 string、number、select、datetime、date、boolean、image、color、textarea |
| 自定义字段 | 支持添加自定义字段(不在预定义列表中) |
| 字段验证 | 支持必填、数字范围、正则表达式验证 |
| JSON 原文编辑 | 支持 Modal 弹窗直接编辑 JSON 代码 |
| 图片上传 | 集成 JImageUpload 组件 |
| 日期选择 | 支持日期和日期时间选择器 |
Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| jsonFields | JSON 字段配置 | JsonField[] | [] |
| formValues | 表单值 | FormValues | {} |
| disabled | 是否禁用 | boolean | false |
Emits
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| update:formValues | 表单值变化时触发 | (value: FormValues) => void |
| validate | 验证状态变化时触发 | (errors: Record<string, string>) => void |
Expose
| 方法名 | 说明 | 类型 |
|---|---|---|
| validate | 执行表单验证 | () => Promise<boolean> |
| clearForm | 清空表单 | () => void |
TypeScript 类型定义
// 字段值类型
type FieldValueType = string | number | boolean | Date | null | undefined;
// 选择项选项
interface SelectOption {
value: string | number;
label: string;
disabled?: boolean;
}
// JSON 字段定义
interface JsonField {
key: string; // 字段唯一标识
label: string; // 字段显示标签
type?: FieldType | string;// 字段类型
options?: SelectOption[]; // 选择类型的选项
defaultValue?: FieldValueType; // 默认值
required?: boolean; // 是否必填
placeholder?: string; // 占位符提示
description?: string; // 字段描述/帮助信息
disabled?: boolean; // 是否禁用
hidden?: boolean; // 字段是否隐藏
min?: number; // 字段最小值(number 类型)
max?: number; // 字段最大值(number 类型)
pattern?: RegExp; // 正则验证(string 类型)
validateMessage?: string; // 验证错误提示
}
// 表单值类型
interface FormValues {
[key: string]: FieldValueType;
}字段类型说明
| 类型值 | 说明 | 组件 | 示例配置 |
|---|---|---|---|
string | 文本输入 | Input | { key: 'name', label: '姓名', type: 'string' } |
textarea | 多行文本 | Textarea | { key: 'desc', label: '描述', type: 'textarea' } |
number | 数字输入 | InputNumber | { key: 'age', label: '年龄', type: 'number', min: 0, max: 150 } |
select | 下拉选择 | Select | { key: 'gender', label: '性别', type: 'select', options: [...] } |
datetime | 日期时间 | DatePicker(showTime) | { key: 'createTime', label: '创建时间', type: 'datetime' } |
date | 日期 | DatePicker | { key: 'birthday', label: '生日', type: 'date' } |
boolean | 布尔值 | Select(是/否) | { key: 'isShow', label: '是否显示', type: 'boolean' } |
image | 图片上传 | JImageUpload | { key: 'avatar', label: '头像', type: 'image' } |
color | 颜色选择 | Input + Color Input | { key: 'bgColor', label: '背景色', type: 'color' } |
使用示例
基础用法
<template>
<JsonScheme
:jsonFields="jsonFields"
:formValues="formValues"
@update:formValues="handleUpdate"
@validate="handleValidate"
/>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import JsonScheme from '@/components/Json/JsonScheme.vue';
const jsonFields = ref([
{ key: 'name', label: '姓名', type: 'string', required: true },
{ key: 'age', label: '年龄', type: 'number', min: 0, max: 150 },
{ key: 'gender', label: '性别', type: 'select', options: [
{ value: 'male', label: '男' },
{ value: 'female', label: '女' }
]
},
{ key: 'birthday', label: '生日', type: 'date' },
{ key: 'isMarried', label: '是否已婚', type: 'boolean' },
{ key: 'profilePic', label: '个人照片', type: 'image' },
{ key: 'favoriteColor', label: '喜欢的颜色', type: 'color' },
{ key: 'bio', label: '个人简介', type: 'textarea' }
]);
const formValues = ref({
name: '张三',
age: 25,
gender: 'male',
birthday: '1998-05-20',
isMarried: false,
profilePic: '',
favoriteColor: '#ff0000',
bio: ''
});
const handleUpdate = (values) => {
console.log('表单值变化:', values);
};
const handleValidate = (errors) => {
console.log('验证错误:', errors);
};
</script>验证配置
const jsonFields = [
{
key: 'email',
label: '邮箱',
type: 'string',
required: true,
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
validateMessage: '请输入有效的邮箱地址'
},
{
key: 'amount',
label: '金额',
type: 'number',
required: true,
min: 0,
max: 1000000,
validateMessage: '金额必须在 0 到 1,000,000 之间'
}
];调用验证方法
<template>
<JsonScheme ref="schemeRef" :jsonFields="jsonFields" v-model:formValues="formValues" />
<a-button @click="handleSubmit">提交</a-button>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import JsonScheme from '@/components/Json/JsonScheme.vue';
const schemeRef = ref();
const formValues = ref({});
const handleSubmit = async () => {
const isValid = await schemeRef.value.validate();
if (isValid) {
console.log('验证通过,提交数据:', formValues.value);
} else {
console.log('验证失败');
}
};
</script>3. JsonSchemeForm 组件
功能特性
JsonSchemeForm 是 JsonScheme 的包装组件,专门用于 BasicForm 集成:
- 自动处理 v-model 双向绑定
- 触发 change 和 update:value 事件
- 转发 validate 事件
- 暴露 validate 方法供外部调用
Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| value | 表单值(v-model) | FormValues | {} |
| jsonFields | JSON 字段配置 | JsonField[] | - |
| disabled | 是否禁用 | boolean | false |
Emits
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| change | 表单值变化时触发 | (value: FormValues) => void |
| update:value | v-model 更新事件 | (value: FormValues) => void |
| validate | 验证状态变化时触发 | (errors: Record<string, string>) => void |
Expose
| 方法名 | 说明 | 类型 |
|---|---|---|
| validate | 执行表单验证 | () => Promise<boolean> |
BasicForm 集成使用
在 BasicForm 的 data.ts 中配置:
// 表单列配置
export const formSchema: FormSchema[] = [
{
label: '预约信息',
field: 'reservationInfo',
component: 'JsonSchemeForm',
componentProps: {
jsonFields: [
{
key: 'textButton',
type: 'string',
label: '按钮名称',
defaultValue: '立即预约'
},
{
key: 'colorButton',
type: 'color',
label: '按钮颜色'
},
{
key: 'max',
type: 'number',
label: '最大预约数量',
defaultValue: 1,
min: 1,
max: 100
},
{
key: 'isShow',
type: 'boolean',
label: '是否展示',
defaultValue: true
},
{
key: 'bg',
type: 'image',
label: '背景图片'
},
{
key: 'date',
type: 'date',
label: '日期'
},
],
},
}
];完整页面示例
<template>
<BasicForm @register="registerForm" @submit="handleSubmit" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './data';
const [registerForm, { getFieldsValue }] = useForm({
labelWidth: 120,
schemas: formSchema,
actionColOptions: { span: 24 },
submitButtonOptions: { text: '提交' },
resetButtonOptions: { text: '重置' },
});
const handleSubmit = (values) => {
console.log('提交的表单数据:', values);
// values.reservationInfo 包含 JSON 表单的数据
};
</script>4. 组件导出
// src/components/Json/index.ts
export { default as JsonPopover } from './JsonPopover.vue';
export { default as JsonScheme } from './JsonScheme.vue';
export { default as JsonSchemeForm } from './JsonSchemeForm.vue';
export * from './types';5. 完整类型定义文件
/**
* JSON Schema 表单类型定义
*/
/**
* 字段值类型
*/
export type FieldValueType = string | number | boolean | Date | null | undefined;
/**
* 字段类型枚举
*/
export enum FieldType {
STRING = 'string',
NUMBER = 'number',
SELECT = 'select',
DATETIME = 'datetime',
DATE = 'date',
BOOLEAN = 'boolean',
IMAGE = 'image',
COLOR = 'color',
TEXTAREA = 'textarea',
}
/**
* 选择项选项
*/
export interface SelectOption {
/** 选项值 */
value: string | number;
/** 选项标签 */
label: string;
/** 是否禁用 */
disabled?: boolean;
}
/**
* JSON 字段定义
*/
export interface JsonField {
/** 字段唯一标识 */
key: string;
/** 字段显示标签 */
label: string;
/** 字段类型 */
type?: FieldType | string;
/** 选择类型的选项 */
options?: SelectOption[];
/** 默认值 */
defaultValue?: FieldValueType;
/** 是否必填 */
required?: boolean;
/** 占位符提示 */
placeholder?: string;
/** 字段描述/帮助信息 */
description?: string;
/** 是否禁用 */
disabled?: boolean;
/** 字段是否隐藏 */
hidden?: boolean;
/** 字段最小值(number 类型) */
min?: number;
/** 字段最大值(number 类型) */
max?: number;
/** 正则验证(string 类型) */
pattern?: RegExp;
/** 验证错误提示 */
validateMessage?: string;
}
/**
* 表单值类型
*/
export interface FormValues {
[key: string]: FieldValueType;
}
/**
* 表单行数据
*/
export interface FormRow {
/** 字段 key */
key: string;
/** 字段值 */
value: FieldValueType;
/** 行唯一标识 */
id?: string | number;
/** 是否为自定义字段 */
isCustom?: boolean;
/** 自定义字段的类型 */
customType?: string;
}
/**
* 验证错误信息
*/
export interface ValidationError {
/** 字段 key */
key: string;
/** 错误信息 */
message: string;
}
/**
* JSON Popover 属性
*/
export interface JsonPopoverProps {
/** JSON 数据(对象或字符串) */
json: Record<string, any> | string;
/** Popover 标题 */
title?: string;
/** 是否始终显示 Popover(不悬停) */
alwaysShow?: boolean;
/** 预览文本的最大长度 */
previewLength?: number;
/** 是否显示字段数量摘要 */
showSummary?: boolean;
/** 最大高度 */
maxHeight?: string;
/** 最大宽度 */
maxWidth?: string;
/** 字段定义配置(用于显示友好名称) */
jsonFields?: JsonField[];
}6. 最佳实践
JsonPopover 使用建议
- 表格中展示 JSON 字段:使用 customRender 配合 h 函数
- 提供有意义的标题:标题应包含关键信息,如"等级名称 - 配置"
- 启用摘要:使用 showSummary: true 显示配置项数量
- 传入 jsonFields:配置字段定义以显示友好名称和描述
JsonScheme 使用建议
- 定义完整的字段配置:包括 label、type、required、description 等
- 合理设置默认值:使用 defaultValue 属性
- 配置验证规则:使用 required、min、max、pattern 等属性
- 自定义字段支持:组件自动处理不在预定义列表中的字段
表单集成建议
- 使用 JsonSchemeForm:在 BasicForm 中使用 JsonSchemeForm 而非直接使用 JsonScheme
- 字段复用:将 jsonFields 配置提取为常量,多处复用
- 数据验证:在提交前调用 validate 方法确保数据有效
7. 相关组件
- BasicForm: 基础表单组件
- JImageUpload: 图片上传组件
- CodeEditor: 代码编辑器组件(用于 JSON 原文编辑)
8. 更新日志
| 版本 | 日期 | 说明 |
|---|---|---|
| 3.7.3 | 2025-01-20 | 初始版本 |
| 3.7.4 | 2026-04-22 | 添加 JsonPopover 组件,重构文档 |