vue antd 基于json schema 的动态表单实现 三: 实现

介绍

本篇文章主要介绍基于json schema 实现 vue antd 的动态表单中的第三部分:实现。
介绍如何解析 json schema 和 ui schema 代码实现!


源代码实现

DyForm

动态表单的容器,主要负责解析 json shcema 和 uischema,以及提供表单项加载容器

<template>
<a-form @submit="handleSubmit"
    style="margin-top: 8px"
    :autoFormCreate="(form)=>{this.form = form}"
    v-bind="formOption">

    <dy-item :properties="rootProperties"></dy-item>

    <a-form-item style="margin-top: 32px">
        <a-button type="primary" htmlType="submit" :loading="submiting">
            提交
        </a-button>
        <a-button style="margin-left: 8px">保存</a-button>
    </a-form-item>

</a-form>
</template>

<style lang="less">

</style>

<script lang="tsx">
import {
    Component,
    Prop,
    Vue,
    Emit,
} from 'vue-property-decorator';
import {
    State,
    Mutation,
    namespace,
} from 'vuex-class';

import DyFormitem from './DyFormitem.vue';
import { DFSchema } from './schema/DfSchema';
import { DFUISchema } from './schema/UiSchema';
import FormProperty from './domain/FormProperty';

@Component({
    components: {
        'dy-item': DyFormitem,
    },
})
export default class DyForm extends Vue {

    /**
     * json schema 描述的表单结构
     */
    @Prop({
        type: Object,
        default() {
            return {};
        },
    })
    private formSchema!: DFSchema;

    /**
     * UI schema 描述表单渲染
     */
    @Prop({
        type: Object,
        default() {
            return {};
        },
    })
    private uiSchema!: DFUISchema;

    /**
     * 表单选项,未使用
     */
    @Prop({
        type: Object,
        default() {
            return {};
        },
    })
    private formOption!: any;

    /**
     * 表单是否提交中
     */
    @Prop({
        type: Boolean,
        default: false,
    })
    private submiting!: boolean;

    private form: any = null;

    private rootProperties: FormProperty[] = [];

    private mounted() {
        this.rootProperties = this.createRootProperties();
    }

    /**
     * 创建属性
     */
    private createRootProperties() {
        const properties: any = this.formSchema.properties;
        const rootProperties = Object.keys(properties)
            .map((key: any) => {
                const item = properties[key];
                const uiItem = this.uiSchema[key];
                return new FormProperty(key, item, uiItem, this.formSchema.required);
            });
        return rootProperties;
    }

    /**
     * 表单提交
     */
    private handleSubmit(e: any) {
        e.preventDefault();

        this.form.validateFieldsAndScroll((err: any, values: any) => {
            if (err) {
                return;
            }
            this.success(values);
        });

    }

    @Emit('onSuccess')
    private success(values: any) {

    }

}
</script>

DyFormitem

主要是动态表单项form-item的展示容器,根据dy-form组件中传递解析后的form属性进行表单渲染

<template>
<div>
    <component v-for="(formitem,index) in properties" 
    :key="index" 
    :is="createWidgets(formitem)"
    :formitem="formitem"></component>
</div>
</template>

<style lang="less">

</style>

<script  lang="tsx">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { State, Mutation, namespace } from 'vuex-class';

import registry from './WidgetRegistry';

@Component({
    components: {},
})
export default class DyFormitem extends Vue {

    @Prop({type: Array, default() {
        return [];
    }})
    private properties!: any[];

    /**
     * 从 组件工厂中获取组件并显示
     */
    private createWidgets(foritem: any): any {
        const key = `df-${foritem.type}`;
        const comp = registry.getType(key);
        return comp;
    }

}
</script>

dyformitemMixin

动态表单项和表单组件的混入,提炼每个组件需要的公共方法和属性

import { Observable, Subscription, BehaviorSubject } from 'rxjs';
import {
    Component,
    Prop,
    Vue,
    Emit,
    Model,
    Watch,
} from 'vue-property-decorator';

import { DFSchema } from './schema/DfSchema';
import FormProperty from './domain/FormProperty';

export interface IDyFormMixin {
    formitem?: FormProperty;
}

/**
 * 动态表单项组件的混入
 */
@Component({})
export default class DyFormMixin extends Vue implements IDyFormMixin {

    /**
     * 表单属性
     */
    @Prop({type: Object, default: () => {}})
    public formitem!: FormProperty;

    /**
     * 组件属性
     */
    get widgetAttrs() {
        return this.formitem.widgetAttrs;
    }

    /**
     * form-item 属性
     */
    get itemAttrs() {
        return this.formitem.formitemAttrs;
    }

    /**
     * 标签
     */
    get label(): string {
        return this.formitem.label;
    }

}

StringWidget

文本框组件

<template>
<df-item :formitem="formitem">
  <a-input v-bind="widgetAttrs"/>
</df-item>
</template>

<style lang="less">

</style>

<script  lang="ts">
import { Component, Prop, Vue, Mixins } from 'vue-property-decorator';
import { State, Mutation, namespace } from 'vuex-class';

import { DFSchema } from './../schema/DfSchema';

import DyFormitemWapper from './../DyFormitemWapper.vue';

import DyFormMixin, { IDyFormMixin } from '@/components/dynamicform/dyformitemMixin';

@Component({
    components: {
      'df-item': DyFormitemWapper,
    },
})
export default class StringWidget extends  Mixins<IDyFormMixin>(DyFormMixin) {

}
</script>

其他动态表单的组件编写和 StringWidget保持同样的代码,只不过是将a-input转换为其他组件

WidgetRegistry

动态表单组件注册类, 提供注册和获取方法

import { Component, Prop, Vue } from 'vue-property-decorator';

/**
 * 动态表单组件注册类
 * 提供注册和获取方法
 */
class WidgetRegistry {

    private widgets: { [type: string]: any } = {};

    private defaultWidget: any;

    /**
     * 设置默认组件,以便找不到type对应的逐渐时候显示
     * @param widget
     */
    public setDefault(widget: any) {
        this.defaultWidget = widget;
    }

    /**
     * 注册动态表单组件
     * @param type
     * @param widget
     */
    public register(type: string, widget: any) {
        this.widgets[type] = widget;
    }

    /**
     * 判断指定的组件名称是否存在
     * @param type
     */
    public has(type: string) {
        return this.widgets.hasOwnProperty(type);
    }

    /**
     * 根据指定类型获取动态组件
     * @param type
     */
    public getType(type: string): any {
        if (this.has(type)) {
            return this.widgets[type];
        }
        return this.defaultWidget;
    }

}

const widgetRegistry = new WidgetRegistry();
export default widgetRegistry;

注册组件见代码

// 日期范围
        registry.register('df-daterange', DateRangeWidget);

        // 数字输入框
        registry.register('df-number', NumberWidget);

        // 文本框
        registry.register('df-string', StringWidget);
        registry.register('df-text', TextWidget);

        // 区域文本框
        registry.register('df-textarea', TextareaWidget);

        // 开关
        registry.register('df-boolean', SwitchWidget);

        // 拖动条
        registry.register('df-slider', SliderWidget);

        // 星打分
        registry.register('df-rate', RateWidget);

        // 下拉框
        registry.register('df-select', SelectWidget);

        // 单选框
        registry.register('df-radio', RadioWidget);

        // 上传文件
        registry.register('df-upload', UploadWidget);
        registry.register('df-uploaddragger', UploadDraggerWidget);

FormProperty

form属性,主要是提供一些属性,提供给动态表单项属性,
一般是由json shcme 和ui shcmea组成

import { DFSchema } from './../schema/DfSchema';
import { DFUISchemaItem } from './../schema/UiSchema';


// tslint:disable:variable-name
/**
 * form属性,主要是提供一些属性,提供给动态表单项属性
 * 一般是有 json schem 和 ui shcem 和 formdata组合提供
 */
export default class FormProperty {
    public formData: any = {};

    private _formSchem: DFSchema = {};
    private _uiSchema: DFUISchemaItem = {};
    private _propertyId: string = '' ;

    private _required: string[] = [];

    constructor(
        propertyId: string ,
        formSchema: DFSchema,
        uiSchema: DFUISchemaItem,
        required: string[] = []) {
        this._propertyId = propertyId;
        this._formSchem = formSchema;
        this._uiSchema = uiSchema;
        this._required = required;
    }

    get key(): string {
        return this._propertyId;
    }

    get id(): string {
        return `$$${this._propertyId}`;
    }

    get formSchema(): DFSchema {
        if (this._formSchem == null) {
            return {};
        }
        return this._formSchem;
    }

    get uiSchema(): DFUISchemaItem {
        const itemui: any = this.formSchema.ui;
        const ui: any = this._uiSchema;
        return {
            ...itemui,
            ...ui,
        };
    }

    get type() {
        if (this.uiSchema.widget) {
            return this.uiSchema.widget;
        }
        return this.formSchema.type;
    }

    get formitemAttrs() {
        const attrs = this.ui.itemattrs;
        attrs.fieldDecoratorId = this.key;
        attrs.fieldDecoratorOptions = this.fieldDecoratorOptions;
        return attrs;
    }

    get widgetAttrs() {
        return this.ui.widgetattrs;
    }

    get ui(): any {
        const propertyUi: any = this.formSchema.ui;
        const ui = {
            ...propertyUi,
            ...this.uiSchema,
        };
        return ui;
    }

    get label(): string {
        if (this.formSchema.title) {
            return this.formSchema.title;
        }
        if (this.uiSchema.widgetattrs && this.uiSchema.widgetattrs.label) {
            return this.uiSchema.widgetattrs.label;
        }
        return this.key;
    }

    get listSource(): any[] {
        if (!this.formSchema.enum) {
            return [];
        }
        return this.formSchema.enum;
    }

    get rules(): any[] {
        const rules: any[] = [];
        const isRequired = this._required.includes(this.key);
        if (isRequired) {
            let msg = '必填项';
            if (this.ui.errors) {
                msg = this.ui.errors.required;
            }
            rules.push({ required: true, message: msg });
        }
        if (this.formSchema.maxLength) {
            let msg = '超过最大长度';
            if (this.ui.errors) {
                msg = this.ui.errors.maxLength;
            }
            rules.push({ max: this.formSchema.maxLength, message: msg });
        }
        if (this.formSchema.minLength) {
            let msg = '最小长度';
            if (this.ui.errors) {
                msg = this.ui.errors.minLength;
            }
            rules.push({ min: this.formSchema.minLength, message: msg });
        }
        if (this.formSchema.pattern) {
            let msg = '正则表达式不正确';
            if (this.ui.errors) {
                msg = this.ui.errors.pattern;
            }
            rules.push({ pattern: this.formSchema.pattern, message: msg });
        }
        if (this.formSchema.maximum) {
            let msg = '最大数';
            if (this.ui.errors) {
                msg = this.ui.errors.maximum;
            }
            rules.push({ type: 'number', max: this.formSchema.maximum, message: msg });
        }
        if (this.formSchema.minimum) {
            let msg = '最小数';
            if (this.ui.errors) {
                msg = this.ui.errors.minimum;
            }
            rules.push({ type: 'number', min: this.formSchema.minimum, message: msg });
        }
        // { required: true, message: '请输入姓名' }
        return rules;
    }

    get fieldDecoratorOptions(): any {
        return {
            initialValue: this.formData[this.key],
            rules: this.rules,
        };
    }
}


参考资料

ng-alain-form
json shcema
antd-vue


我的公众号

abp爱好者
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容

  • 介绍 本篇文章主要介绍基于json schema 实现 vue antd 的动态表单中的第二部分:使用。 源码vu...
    诸葛_小亮阅读 6,844评论 7 18
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 亲子日记9 8月7日 今天是孩子放假第二天,儿子早晨早早就起来了,跟我说,妈妈我不去上学,在家跟你一块做家务,哄弟...
    马佳浩妈妈阅读 213评论 0 0
  • js生成验证码其实原理很简单,第一就是创建画布,第二获取验证码,第三将验证码画到画布上,接下来就看代码吧! 添加画...
    Me小酥酥阅读 7,200评论 0 4
  • 清晨,我坐在大树底下等图书馆开门。手里有咖啡和书。 大门前早已排队一百多号人,因为躲着阳光,在屋檐下顺着建筑物的影...
    小久_ab87阅读 307评论 0 0