vue antd 基于json schema 的動態(tài)表單實現(xiàn) 三: 實現(xiàn)

介紹

本篇文章主要介紹基于json schema 實現(xiàn) vue antd 的動態(tài)表單中的第三部分:實現(xiàn)。
介紹如何解析 json schema 和 ui schema 代碼實現(xiàn)!


源代碼實現(xiàn)

DyForm

動態(tài)表單的容器,主要負責解析 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();
    }

    /**
     * 創(chuàng)建屬性
     */
    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

主要是動態(tài)表單項form-item的展示容器,根據(jù)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

動態(tài)表單項和表單組件的混入,提煉每個組件需要的公共方法和屬性

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;
}

/**
 * 動態(tài)表單項組件的混入
 */
@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>

其他動態(tài)表單的組件編寫和 StringWidget保持同樣的代碼,只不過是將a-input轉換為其他組件

WidgetRegistry

動態(tài)表單組件注冊類, 提供注冊和獲取方法

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

/**
 * 動態(tài)表單組件注冊類
 * 提供注冊和獲取方法
 */
class WidgetRegistry {

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

    private defaultWidget: any;

    /**
     * 設置默認組件,以便找不到type對應的逐漸時候顯示
     * @param widget
     */
    public setDefault(widget: any) {
        this.defaultWidget = widget;
    }

    /**
     * 注冊動態(tài)表單組件
     * @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);
    }

    /**
     * 根據(jù)指定類型獲取動態(tài)組件
     * @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);

        // 數(shù)字輸入框
        registry.register('df-number', NumberWidget);

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

        // 區(qū)域文本框
        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屬性,主要是提供一些屬性,提供給動態(tài)表單項屬性,
一般是由json shcme 和ui shcmea組成

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


// tslint:disable:variable-name
/**
 * form屬性,主要是提供一些屬性,提供給動態(tài)表單項屬性
 * 一般是有 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 = '最大數(shù)';
            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 = '最小數(shù)';
            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愛好者
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 介紹 本篇文章主要介紹基于json schema 實現(xiàn) vue antd 的動態(tài)表單中的第二部分:使用。 源碼vu...
    諸葛_小亮閱讀 7,326評論 7 18
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評論 19 139
  • 親子日記9 8月7日 今天是孩子放假第二天,兒子早晨早早就起來了,跟我說,媽媽我不去上學,在家跟你一塊做家務,哄弟...
    馬佳浩媽媽閱讀 230評論 0 0
  • js生成驗證碼其實原理很簡單,第一就是創(chuàng)建畫布,第二獲取驗證碼,第三將驗證碼畫到畫布上,接下來就看代碼吧! 添加畫...
    Me小酥酥閱讀 7,291評論 0 4
  • 清晨,我坐在大樹底下等圖書館開門。手里有咖啡和書。 大門前早已排隊一百多號人,因為躲著陽光,在屋檐下順著建筑物的影...
    小久_ab87閱讀 363評論 0 0

友情鏈接更多精彩內容