antd-vue table 动态添加必填项

首先我们使用 async-validator 库进行校验. 详情内容请查看: 使用 async-validator 自定义校验规则实现 table 组件的循环表单校验功能.

校验方式跟上述案例是一致的.代码如下:

import Schema from 'async-validator'

// 校验
validate (validateProp, rules, value) {
  // 真正校验的的时候再生成validator函数
  if (!validateProp || !rules) return Promise.resolve(true)
  const descriptor = {
    [validateProp]: rules,
  }
  const validator = new Schema(descriptor)
  if (!validator) return Promise.resolve(true)
  const model = {
    [validateProp]: value,
  }
  return validator.validate(model, (errors, fields) => {
    const errorMessage = errors ? errors[0].message : ''
    return !errorMessage
  })
},

如何动态添加字段的校验规则呢?

const requiredRule = [{ required: true, message: '该选项必填' }]
async handleValidate () {
  const length = this.tableData.length
  // this.tableData 为 商品 table
  for (let index = 0; index < length; index++) {
    for await (let form of (this.tableData[index].extraInfo || [])) {
      // 必填校验
      if (form.required) {
        try {
          // 调用校验方法 validate
          await this.validate(form.attrField, requiredRule, this.tableData[index][form.attrField])
        } catch (err) {
          this.$antdMessage.warning(`请完善第 ${index + 1} 行货物补充信息`)
          return Promise.resolve(false)
        }
      }
    }
  }
  return Promise.resolve(true)
},

提交调用

async handleSubmit () {
  const { tableData, validate, deleteIds } = this.$refs.goods
  if (tableData.length === 0) {
    return this.$antdMessage.warning('请至少添加一条商品信息')
  } else {
    // 强制更新货物补充信息
    this.$refs.info.getData(tableData)
    let isVerify = await this.$refs.info.handleValidate()
    if (!isVerify) return
  }
  ......
},

getData 方法

getData (val) {
  this.tableData = [...val].map((item) => {
    return this.handleData(item)
  })
},

handleData 数据处理

handleData (row) {
  let initForm = []
  let data = this.sourceData.find(item => item.bindDimensionCode === row.varietyCode)
  if (data === undefined || (data.bindDimensionAttrs && !data.bindDimensionAttrs.length)) {
    // 兼容入库
    if (this.modal === 'orderIn') {
      return { ...row }
    }
    return []
  }
  data.bindDimensionAttrs.forEach(formItem => {
    initForm.push({
      ...formItem,
      attrValueCode: row[formItem.attrField],
      // select 下拉框
      attrValueName: formItem.attrType === 'OPTION' ? row[`${formItem.attrField}Name`] : row[formItem.attrField],
    })
  })
  return { ...row, extraInfo: initForm }
},

监听 data 源数据

watch: {
  data: {
    async handler (val) {
      if (!val) return (this.tableData = [])
      this.sourceData = await this.getInit()
      this.getData(val)
    },
    deep: true,
  },
},

async getInit () {
  const { data } = await Common.getInvAttrField({ userRange: this.userRange })
  return data
},

你可能感兴趣的:(ant-design-vue,antd-vue,table,动态添加必填项)