跳到内容
SCRM DOC
前端组件库业务组件JsonVue3创建于2025-01-20更新于 2026-04-22

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

参数说明类型默认值
jsonJSON 数据(对象或字符串)Record<string, any> | string | null-
titlePopover 标题string'JSON 配置'
alwaysShow是否始终显示 Popover(不悬停)booleanfalse
previewLength预览文本的最大长度number50
showSummary是否显示字段数量摘要booleantrue
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

参数说明类型默认值
jsonFieldsJSON 字段配置JsonField[][]
formValues表单值FormValues{}
disabled是否禁用booleanfalse

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{}
jsonFieldsJSON 字段配置JsonField[]-
disabled是否禁用booleanfalse

Emits

事件名说明回调参数
change表单值变化时触发(value: FormValues) => void
update:valuev-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 使用建议

  1. 表格中展示 JSON 字段:使用 customRender 配合 h 函数
  2. 提供有意义的标题:标题应包含关键信息,如"等级名称 - 配置"
  3. 启用摘要:使用 showSummary: true 显示配置项数量
  4. 传入 jsonFields:配置字段定义以显示友好名称和描述

JsonScheme 使用建议

  1. 定义完整的字段配置:包括 label、type、required、description 等
  2. 合理设置默认值:使用 defaultValue 属性
  3. 配置验证规则:使用 required、min、max、pattern 等属性
  4. 自定义字段支持:组件自动处理不在预定义列表中的字段

表单集成建议

  1. 使用 JsonSchemeForm:在 BasicForm 中使用 JsonSchemeForm 而非直接使用 JsonScheme
  2. 字段复用:将 jsonFields 配置提取为常量,多处复用
  3. 数据验证:在提交前调用 validate 方法确保数据有效

7. 相关组件

  • BasicForm: 基础表单组件
  • JImageUpload: 图片上传组件
  • CodeEditor: 代码编辑器组件(用于 JSON 原文编辑)

8. 更新日志

版本日期说明
3.7.32025-01-20初始版本
3.7.42026-04-22添加 JsonPopover 组件,重构文档

本页目录