1.循环vxe-table-column
例如下方代码,根据departList的长度,先循环出你需要的表格表头
<vxe-table :loading="tableLoading" :edit-rules="validRules" keep-source resizable border="" ref="xTable" height="480" :data="tableData" :edit-config="{trigger: 'click', mode: 'cell'}" :scroll-x="{gt: 10}" :scroll-y="{gt: 10}">
<vxe-table-column type="seq" width="60"></vxe-table-column>
<vxe-table-colgroup :title="item.departName" align="center":field="item.departNameId" v-for="(item,index) in departList" :key="index">
<vxe-table-column :field="'yearCount_'+index" title="年度+临时" width="100">
<template v-slot="{ row }">
<span v-if="row['haveDep_'+index]==1"> {{row['yearCount_'+index]}} <span v-if="row['tempCount_' + index]">+ </span>{{row['tempCount_'+index]}}</span>
<span v-else>-</span>
</template>
</vxe-table-column>
<vxe-table-column :field="'hasDistribut_'+index" title="已分配" width="100"></vxe-table-column>
<vxe-table-column :field="'noEnough_'+index" title="未满足" width="100"></vxe-table-column>
<vxe-table-column :field="'distributCount_'+index" width="100" title="本次分配" :edit-render="{name: '$input', props: {type: 'integer',min:0}}">
<!-- <template v-slot:edit="{ row }">
<vxe-input v-if="row['haveDep_'+index]==1" type="number" min=0 v-model="row['distributCount_'+index]" ></vxe-input>
<span v-else>-</span>
</template> -->
</vxe-table-column>
</vxe-table-colgroup>
</vxe-table>
2.现在需要对hasDistribut这个字段进行校验,但是这个字段在经过循环后,已经衍生成hasDistribut_0 . hasDistribut_1 .hasDistribut_2 .hasDistribut_3等等,在data里面肯定无法直接定义了,需要在生成departList的地方将hasDistribut的校验也循环生成。
data() {
return {
validRules: {},
}
}
this.departList.forEach((ele,depIndex)=>{
this.validRules['distributCount_' + depIndex] = [{
validator: ({
cellValue,
rule,
rules,
row,
rowIndex,
column,
columnIndex
}) => {
let total = 0
for (let key in row) {
if (key.indexOf('distributCount') != -1) {
let num = (row[key] == null || row[key] == '-') ? 0 : row[key]
total = total + Number(num)
}
}
console.log(cellValue, row.storageCount - total)
if (row.storageCount - total < 0) {
return new Error('分配总和大于库存量')
}
}
}]
})
3.这样edit的时候校验就生效了,最终保存的时候进行快速校验。不通过不能保存
async handleSubmit(val) {
const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
if (errMap) {
this.$XModal.message({
status: 'error',
message: '校验不通过!'
})
return false
}
}
edit-rules的快速校验有一个特点,就是发生了edit的表格才会校验,如果这个数据是初始化带来的的,一样可以通过校验。