json配置化el-form

533 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

前言

不知道大家平时是怎么使用element-ui中的el-form组件?是否会跟我一样觉得不够灵活,根据官网的例子,每次使用时都不得不去写一大堆的el-form-item。如果需求发生了改变,需要对某个字段进行位置更改或者添加删除之类的操作,那么不得不在一大堆el-form-item中找出需要更改的标签,并不是十分方便,也不直观。

因此,在网上进行相关方面的查找学习之后,整理出一个由json来配置el-form的思路。

基本思路

首先,定义一个以下的json:

const fieldType = {
    label: '', // 字段名称
    prop: '', // el-form-item 的 prop
    type: '', // 该字段在表单中对应的操作类型,如input, select, date-picker等等
    ... // 以及一些其他需要用到数据,比如el-select的选项之类
}

使用以上的json组成数组formInfo来记录表单中的字段,然后通过使用v-for进行渲染,当然,需要先在el-form中定义好需要用到的inputselectdate-picker等标签,示例如下:

<el-form
   ref="form"
   :model="form"
   :rules="formRules"
   label-width="100px"
>
   <template v-for="(item, index) in formInfo">
       <el-form-item :key="item.prop + index" :prop="item.prop" :label="item.label">
           <template v-if="item.type === 'input'">
              <el-input v-model="form[item.prop]" />
           </template>
           
           <template v-if="item.type === 'textarea'">
              <el-input v-model="form[item.prop]" type="textarea" />
           </template>
           
           <template v-if="item.type === 'select'">
              <el-select v-model="form[item.prop]" style="width: 100%">
                  <el-option
                     v-for="option in item.optionList"
                     :key="option.id"
                     :label="option.label"
                     :value="option.id">
                  </el-option>
              </el-select>
           </template>
           .....
       </el-form-item>
   </template>
</el-form>

el-form中,已经事先定义好了表单中需要用到的各种输入操作标签,依靠字段信息中type来进行区分,同时,字段信息中还可以带上其他信息,比如上面代码中el-select用到的选项列表optionList 。这样,基本上就能通过一个如下的json数组来控制表单中显示的内容:

const formInfo = [
    { label: '名字', prop: 'name', type: 'input' },
    { label: '简介', prop: 'introduction', type: 'textares' },
    {
        label: '性别',
        prop: 'sex',
        type: 'select',
        optionsList: [ { id: 1, label: '男' }, { id: 2, label: '女' } ]
    },
    .......
]

如果需要对表单进行增删查改,那么直接更改formInfo中的数据即可即可实现,十分直观、便利。