vue3+antd table 只校验选中的数据中必填字段

 - 动态校验层级较深的必填字段、自定义校验
 

```html
<template>
  <a-button type="primary" ghost @click="handleSubmit"></a-button>
  <a-form :model="tableData" ref="tableFormRef">
    <a-table
      :columns="columns"
      :data-source="tableData"
      :row-selection="rowSelection"
      :rowKey="(record) => record.id"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === firstContactListName">
          <span v-for="(item, ind) in firstContactList" :key="ind">
          // 校验联系人name必填
          // isSeledted返回值为true时,给a-form-item加name的规则 否则为null 没有规则就不校验;
            <a-form-item
              :name="isSeledted(record) ? [index, 'firstContactList', ind, 'name'] : null"
              :rules="{
                message: '联系人name必填',
                trigger: 'blur',
                required: true
              }"
            >
              <a-input
                v-model:value="item.name"
                :disabled="record.status === '1' ? true : false"
              />
            </a-form-item>
          </span>
        </template>
      </template>
    </a-table>
  </a-form>
</template>```

```javascript
<script>
import { defineComponent, ref, reactive } from 'vue';
import { message } from 'antd-design-vue';
export default defineComponent({
  setup() {
  	const tableFormRef = ref();
  	const selectedRowIds = ref([]);
  	const selectedRows = ref([]);
  	const rowSelection = reactive({
		fixed: true,
		onChange: (selectedRowKeys, selectedRows) => {
			selectedRowIds.value = selectedRowKeys;
			selectedRows.vaue = selectedRows;
		}
	});
    const columns = ref([
      {
        title: 'first Contact Name',
        detaIndex: 'firstContactList',
        key: 'firstContactListName',
        wdith: 200
      },
      {
        title: 'first Contact Email',
        detaIndex: 'firstContactList',
        key: 'firstContactListEmail',
        width: 200
      },
      {
      	title: 'Status',
      	detaIndex: 'status',
      	key: 'status'
      }
    ]);
    // 表格数据
    const tableData = ref([
    	{
    		id: '',
    		status: '',
    		statusName: '',
    		createTime: '',
    		firstContactList: [
	    		{
	    			id: '',
	    			name: '',
	    			email: '',
				},
				{
	    			id: '',
	    			name: '',
	    			email: '',
				},
			]
    	}
    ]);
    // 判断是否是选中的数据
    const isSeledted = computed(() => (record) => {
    	return selectedRows.value.some(t => t.id === record.id);
    });
	// 提交
	const handleSubmit = () => {
		tableFormRef.value.validateFields().then(res => {
			if(!selectedRows.value.length) {
				 message.warning('至少选择一条数据');
				 return
			}
			// 接口请求
		}).catch(err => {
			console.log(err);
		})
	}
    return {
      columns,
      tableData,
      tableFormRef,
      handleSubmit,
      isSeledted
    };
  },
});
</script>


版权声明:本文为weixin_37572609原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。