欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

element基于el-form智能的FormSmart表單組件

 更新時間:2022年04月18日 16:11:38   作者:Bug小哥哥  
本文主要介紹了element基于el-form智能的FormSmart表單組件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

目的

  • el-form 表單配置化,后期可以利用后端進行配置表單
  • 支持柵格布局
  • el-form 屬性大部分都支持
  • 公共配置可以統(tǒng)一處理,如trim、input寬度等
  • 最基本的組件,利用這組件后期可以優(yōu)化簡單的新增編輯彈窗寫法

源碼

<script>
export default {
    props: {
        model: {
            type: Object,
            default: () => {},
        },
        rowItems: {
            type: Array,
            default: () => [],
        },
        formItems: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        return {
            _model: {},
        };
    },
    mounted() {
        // 用于重置,時間范圍選擇組件時重置不了endTime
        this._model = { ...this.model };
        // 默認選中光標,設置ref=focus
        this.focus();
    },
    methods: {
        // 處理v-modelv value 值
        hanlderValue(prop) {
            // 時間范圍選擇組件處理
            if (Array.isArray(prop) && prop.length > 0) {
                const [first] = prop;
                if (this.model[first]) {
                    const data = prop.map((key) => this.model[key]);
                    return data;
                }
                return [];
            }
            return this.model[prop];
        },
        // 處理FormItem綁定值
        hanlderFormItemProp(prop) {
            // 時間范圍選擇組件處理
            if (Array.isArray(prop) && prop.length > 0) {
                // 處理時間范圍選擇的
                const [first] = prop;
                return first;
            }
            return prop;
        },
        // 處理改變值
        hanlderModel(prop, value) {
            // 時間范圍選擇組件處理
            if (prop && Array.isArray(prop)) {
                if (Array.isArray(value)) {
                    // 數(shù)組對應值
                    prop.forEach((key, index) => {
                        this.model[key] = value && value.length > 0 ? value[index] : '';
                    });
                } else if ([null, '', undefined].includes(value)) {
                    // 數(shù)組有清除按鈕時,數(shù)組一起清理
                    prop.forEach((key) => {
                        this.model[key] = value;
                    });
                }
            } else {
                this.model[prop] = value;
            }
        },
        focus() {
            this.$nextTick(() => {
                if (this.$refs.focus) {
                    setTimeout(() => {
                        this.$refs.focus.focus();
                    }, 100);
                }
            });
        },
        validate(...props) {
            return this.$refs.form.validate(...props);
        },
        // 對部分字段進行校驗
        validateField(...props) {
            return this.$refs.form.validateField(...props);
        },
        // 對整個表單進行重置
        resetFields() {
            Object.assign(this.model, this._model);
            this.$refs.form.resetFields();
        },
        // 移除表單項的校驗結(jié)果
        clearValidate(...props) {
            this.$refs.form.clearValidate(...props);
        },
    },
    render(createElement) {
        // 父級slots
        // form-item label slot
        const slotLabel = (slotName) => createElement(
            'template',
            {
                slot: 'label',
            },
            this.$slots[slotName],
        );
        // formItem 組件
        const formItem = (item) => createElement(
            'el-form-item',
            {
                props: {
                    ...item,
                    prop: this.hanlderFormItemProp(item.prop),
                },
                scopedSlots: {
                    error: (prop) => this.$scopedSlots[item.slotErrorName] && this.$scopedSlots[item.slotErrorName](prop),
                },
            },
            [
                // 加入label插槽
                item.slotLabelName ? slotLabel(item.slotLabelName) : '',
                // 有插槽優(yōu)先
                item.slotName ? this.$slots[item.slotName] : createElement(item.type || 'el-input', {
                    //
                    ref: item.ref,
                    attrs: {
                        ...item.props,
                    },
                    props: {
                        clearable: true,
                        ...item.props,
                        value: this.hanlderValue(item.prop),
                    },
                    // 加樣式
                    style: {
                        width: '240px',
                        ...(item.props && item.props.style),
                    },
                    on: {
                        ...item.on,
                        change: (value) => {
                            // 重寫change方法
                            if (item.on && item.on.change) {
                                item.on.change(value);
                            }
                            this.hanlderModel(item.prop, value);
                        },
                        // el-input 場景
                        input: (value) => {
                            this.hanlderModel(item.prop, value);
                        },
                    },
                }),
            ],
        );
        // col 組件
        const col = (item) => createElement('el-col', {
            props: {
                ...item,
            },
        }, item.formItem ? [formItem(item.formItem)] : '');
        // row組件
        const row = (item) => createElement('el-row', {
            props: {
                ...item,
            },
        }, item.cols.map((list) => col(list)));
        return createElement(
            'el-form',
            {
                ref: 'form',
                props: {
                    ...this.$attrs,
                    model: this.model,
                },
                on: {
                    ...this.$listeners,
                },
            },
            // rowItems 優(yōu)先
            this.rowItems.length ? this.rowItems.map((item) => row(item)) : this.formItems.map((item) => formItem(item)),
        );
    },
};
</script>

<style lang="scss" module="s"></style>

關(guān)鍵文檔,大部分復制el-form

Attributes

參數(shù)說明類型可選值默認值
model表單數(shù)據(jù)對象object
rules表單驗證規(guī)則object
inline行內(nèi)表單模式booleanfalse
label-position表單域標簽的位置,如果值為 left 或者 right 時,則需要設置 label-widthstringright/left/topright
label-width表單域標簽的寬度,例如 '50px'。作為 Form 直接子元素的 form-item 會繼承該值。支持 autostring
label-suffix表單域標簽的后綴string
hide-required-asterisk是否隱藏必填字段的標簽旁邊的紅色星號booleanfalse
show-message是否顯示校驗錯誤信息booleantrue
inline-message是否以行內(nèi)形式展示校驗信息booleanfalse
status-icon是否在輸入框中顯示校驗結(jié)果反饋圖標booleanfalse
validate-on-rule-change是否在 rules 屬性改變后立即觸發(fā)一次驗證booleantrue
size用于控制該表單內(nèi)組件的尺寸stringmedium / small / mini
disabled是否禁用該表單內(nèi)的所有組件。若設置為 true,則表單內(nèi)組件上的 disabled 屬性不再生效booleanfalse
-分割線-------------
formItems表單內(nèi)組件arrayForm-Item
rowItems表單內(nèi)組件支持layout布局,優(yōu)先等級高于formItemsarrayRow Attributes

Methods

方法名說明參數(shù)
validate對整個表單進行校驗的方法,參數(shù)為一個回調(diào)函數(shù)。該回調(diào)函數(shù)會在校驗結(jié)束后被調(diào)用,并傳入兩個參數(shù):是否校驗成功和未通過校驗的字段。若不傳入回調(diào)函數(shù),則會返回一個 promiseFunction(callback: Function(boolean, object))
validateField對部分表單字段進行校驗的方法Function(props: array | string, callback: Function(errorMessage: string))
resetFields對整個表單進行重置,將所有字段值重置為初始值并移除校驗結(jié)果
clearValidate移除表單項的校驗結(jié)果。傳入待移除的表單項的 prop 屬性或者 prop 組成的數(shù)組,如不傳則移除整個表單的校驗結(jié)果Function(props: array | string)
focus使 input 獲取焦點-
blur使 input 失去焦點,并隱藏下拉框-

Events

事件名稱說明回調(diào)參數(shù)
validate任一表單項被校驗后觸發(fā)被校驗的表單項 prop 值,校驗是否通過,錯誤消息(如果存在)

Slot

name說明
label標簽文本的內(nèi)容

Scoped Slot

name說明
error自定義表單校驗信息的顯示方式,參數(shù)為 { error }

Form-Item Attributes

參數(shù)說明類型可選值默認值
prop表單域 model 字段,在使用 validate、resetFields 方法的情況下,該屬性是必填的string傳入 Form 組件的 model 中的字段
label標簽文本string
label-width表單域標簽的的寬度,例如 '50px'。支持 auto。string
required是否必填,如不設置,則會根據(jù)校驗規(guī)則自動生成booleanfalse
rules表單驗證規(guī)則object
error表單域驗證錯誤信息, 設置該值會使表單驗證狀態(tài)變?yōu)?code>error,并顯示該錯誤信息string
show-message是否顯示校驗錯誤信息booleantrue
inline-message以行內(nèi)形式展示校驗信息booleanfalse
size用于控制該表單域下組件的尺寸stringmedium / small / mini-

Row Attributes

參數(shù)說明類型可選值默認值
gutter柵格間隔number0
type布局模式,可選 flex,現(xiàn)代瀏覽器下有效string
justifyflex 布局下的水平排列方式stringstart/end/center/space-around/space-betweenstart
alignflex 布局下的垂直排列方式stringtop/middle/bottom
tag自定義元素標簽string*div

Col Attributes

參數(shù)說明類型可選值默認值
span柵格占據(jù)的列數(shù)number24
offset柵格左側(cè)的間隔格數(shù)number0
push柵格向右移動格數(shù)number0
pull柵格向左移動格數(shù)number0
xs<768px 響應式柵格數(shù)或者柵格屬性對象number/object (例如: {span: 4, offset: 4})
sm≥768px 響應式柵格數(shù)或者柵格屬性對象number/object (例如: {span: 4, offset: 4})
md≥992px 響應式柵格數(shù)或者柵格屬性對象number/object (例如: {span: 4, offset: 4})
lg≥1200px 響應式柵格數(shù)或者柵格屬性對象number/object (例如: {span: 4, offset: 4})
xl≥1920px 響應式柵格數(shù)或者柵格屬性對象number/object (例如: {span: 4, offset: 4})
tag自定義元素標簽string*div

基本用法

demo 直接使用formItems屬性來配置表單

<template>
  <div>
    <d-form-smart
      ref="form"
      :model="form"
      label-width="150px"
      label-position="left"
      :form-items="formItems"
    >
      <template #slotErrorName>
        <span>按鈕</span>
      </template>
      <template #region-label>
        <el-badge :value="12" class="item">
          <span>自定義label</span>
        </el-badge>
      </template>
      <template #btn>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </d-form-smart>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        form: {
          name: '',
          region: '',
          date: [],
          delivery: false,
          personnel: '',
          radio: '',
          checkbox: [],
          cascader: [],
          timeSelect: '',
          datePicker: '',
          startTime: '',
          endTime: '',
          rate: 0,
          special: '',
          desc: null,
        },
        rules: {
          name: [
            { required: true, message: '請輸入活動名稱', trigger: 'blur' },
            {
              min: 3,
              max: 5,
              message: '長度在 3 到 5 個字符',
              trigger: 'blur',
            },
          ],
        },
        formItems: [
          {
            label: '名字',
            prop: 'name',
            type: 'el-input',
            props: {
              placeholder: '請輸入內(nèi)容',
            },
          },
          {
            label: '開關(guān)',
            prop: 'delivery',
            type: 'el-switch',
          },
          {
            prop: 'region',
            type: 'd-select-smart',
            slotLabelName: 'region-label',
            props: {
              list: [],
            },
          },
          {
            label: '級聯(lián)',
            prop: 'cascader',
            type: 'el-cascader',
            props: {
              options: [
                {
                  value: 'zhinan',
                  label: '指南',
                  children: [
                    {
                      value: 'shejiyuanze',
                      label: '設計原則',
                      children: [
                        {
                          value: 'yizhi',
                          label: '一致',
                        },
                        {
                          value: 'fankui',
                          label: '反饋',
                        },
                        {
                          value: 'xiaolv',
                          label: '效率',
                        },
                        {
                          value: 'kekong',
                          label: '可控',
                        },
                      ],
                    },
                  ],
                },
              ],
            },
          },
          {
            label: '時間選擇',
            prop: 'timeSelect',
            type: 'el-time-select',
            props: {
              placeholder: '選擇時間',
            },
          },
          {
            label: '日期選擇',
            prop: 'datePicker',
            type: 'el-date-picker',
            props: {
              placeholder: '選擇日期',
              valueFormat: 'yyyy-MM-dd',
            },
          },
          {
            label: '日期范圍選擇',
            prop: ['startTime', 'endTime'],
            type: 'el-date-picker',
            props: {
              type: 'daterange',
              startPlaceholder: '開始日期',
              endPlaceholder: '結(jié)束日期',
              format: 'yyyy-MM-dd',
              valueFormat: 'yyyy-MM-dd',
            },
          },
          {
            label: '評分',
            prop: 'rate',
            type: 'el-rate',
          },
          {
            label: '備注',
            prop: 'desc',
            type: 'el-input',
            props: {
              placeholder: '請輸入內(nèi)容',
              type: 'textarea',
              style: {
                width: '400px',
              },
            },
          },
          {
            slotName: 'btn',
            props: {},
          },
        ],
      };
    },
    methods: {
      change(val) {
        console.log('change', val);
      },
      submit(){
           console.log(this.form);
      }
    },
  };
</script>

使用場景

1. 通用列表搜索條件

  • 配置
  queryItems: [
        {
            label: '屬性編碼',
            prop: 'propertyValueCode',
            props: {
                placeholder: '屬性編碼',
            },
        },
        {
            label: '屬性名稱',
            prop: 'name',
            props: {
                placeholder: '屬性名稱',
            },
        },
    ],
  • 模板寫法
    <d-form-smart
        @submit.native.prevent
        ref="query"
        inline
        :model="query"
        label-width="80px"
        label-position="right"
        :form-items="queryItems"
      >
      </d-form-smart>

2.彈窗寫法優(yōu)化

  • 簡單的新增
  • form v-model綁定的值
  • rules 規(guī)則
  • formItems 表單配置
  async add() {
            try {
                // 重置表單
                Object.assign(this.form, this.$options.data().form);
                this.$msgbox({
                    customClass: ['custom-message-box'],
                    title: '新增屬性',
                    message: this.$createElement('FormSmart', {
                        ref: 'form',
                        key: Math.random(), // 重新創(chuàng)建,不緩存
                        attrs: {
                            labelWidth: '100px',
                            labelPosition: 'right',
                            model: this.form,
                            rules: this.opRules,
                            formItems: opItems,
                        },
                    }),
                    closeOnClickModal: false,
                    showCancelButton: true,
                    confirmButtonText: '確定',
                    cancelButtonText: '取消',
                    beforeClose: async (action, instance, done) => {
                        if (action === 'confirm') {
                            await this.$refs.form.validate();
                            instance.confirmButtonLoading = true;
                            try {
                                // 請求接口編寫的地方
                                instance.confirmButtonLoading = false;
                                done();
                            } catch (error) {
                                instance.confirmButtonLoading = false;
                            }
                        } else {
                            this.$refs.form.resetFields();
                            done();
                        }
                    },
                });
            } catch (error) {
                console.error(error);
            }
        },

到此這篇關(guān)于element基于el-form智能的FormSmart表單組件的文章就介紹到這了,更多相關(guān)element FormSmart表單內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論