Vue 动态表单代码示例

154 阅读1分钟

项目里需要用到动态表单的功能,可以在el-form中,对el-form-item循环展示。

要注意的地方有两个,propkey

prop: 循环中的el-form-item对应的prop要设置成带index的.

key: 循环中的元素要带key

更新某个元素时,如果不是表单里的元素,更新时最好用新数组代替。用[...this.dynamicRelateShopForm.shopList]

<template>
<el-form
    ref="editRelateShopRef"
    :model="dynamicRelateShopForm"
    :rules="rules"
    label-width="150px"
    class="distributor-dialog-form"
>
        <el-button @click="addRelateShop" type='text' class="align-right"> <i class="el-icon-plus"></i>新增关联门店</el-button>
        <div class="check-content dialog-form-content">
          <el-form-item
            v-for="(shop, index) in dynamicRelateShopForm.shopList"
            :key="shop.key"
            :label="'关联门店' + (index + 1)"
            :prop="'shopList.' + index + '.shopId'"
            :rules="{
              required: true,
              message: '门店编码不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="shop.shopId" 
              placeholder="请输入门店编码"
              @input="getShopDetail(shop, index)"
              />
            <span>{{ shop.shopName }}</span>
            <el-button type='text' class="del-btn" @click.prevent="removeDynamicShop(shop, index)">
              删除
            </el-button>
          </el-form-item>
        </div>
      </el-form>
<template>  
<script>
      export default {
          name: 'DistributorShop',
          data() {
            return {
                // 动态的表单数组
                dynamicRelateShopForm: {
                    shopList: []
                },
            }
          },
          methods: {
            // 新增关联门店
            addRelateShop() {
              this.dynamicRelateShopForm.shopList.push({
                key: Date.now(),
              });
            },
            // 删除门店
            removeDynamicShop(shop, index) {
              this.dynamicRelateShopForm.shopList.splice(index, 1);
            },
        }
      }
</script>