碰到一个需求,table里面的数据可以添加国家,国家不能重复,大概成果如下。
这是一个循环嵌套的list,琢磨了会才做出来。
模板部分:
<el-form
ref="form"
:model="form"
:inline-message="true"
label-position="left"
label-width="120px"
:rules="rules"
:inline="true">
<el-table :data="form.quarantineProductDeclarationList" border style="width: 100%">
<el-table-column label="序号" :resizable="false" width="50px" type="index" align="center"></el-table-column>
......中间字段省略
<el-table-column label="来自国家和地区数量" :resizable="false" align="center">
<template slot-scope="scope" v-if="scope.row.isSituation">
<div v-for="(item, index) in scope.row.detailList" style="margin: 2px 0; display: flex; align-items: center">
<el-form-item label="" :prop="`quarantineProductDeclarationList[${scope.$index}].detailList[${index}].countryRegion`"
:rules="rules.quarantineProductDeclarationList.detailList.countryRegion">
<back-dict-select dict="国家地区" class="formInput" v-model="item.countryRegion" placeholder="请选择国家" size="mini" :disabled="!isEdit"/>
</el-form-item>
<el-input-number class="tableInput" v-model="item.num" :min="0" size="mini" :disabled="!isEdit"></el-input-number>
<div style="width: 150px; display: flex; flex-shrink: 0">
<el-button v-if="index === scope.row.detailList.length - 1" @click="addDetailList(scope.row.detailList)" size="mini" :disabled="!isEdit">添加一行</el-button>
<el-button @click="delDetailList(scope.row.detailList, index)" size="mini" type="danger" plain :disabled="!isEdit">删除</el-button>
</div>
</div>
</template>
</el-table-column>
</el-table>
</el-form>
js部分:
// 获取quarantineProductDeclarationList及内部数据的工具函数
function getObjectByPath(obj, path, depth = 2) {
let truncatedPath = path
.replace(/\[(\d+)\]/g, '.$1') // 将数组索引 '[0]' 形式转换为 '.0'
.split('.')
.slice(0, depth + 1) // 截取到指定层级(+1 是为了包含数组索引部分)
.join('.'); // 将路径重新拼接成字符串
return truncatedPath
.split('.')
.reduce((acc, key) => acc && acc[key], obj);
}
// 判断有没有重复字段
function hasDuplicateValueByKey(arr, key) {
const seen = {};
for (const item of arr) {
// 假设每个对象都有这个key
if (item.hasOwnProperty(key)) {
const value = item[key];
if (seen[value]) {
// 如果这个值已经被记录在seen中,说明有重复
return true;
}
seen[value] = true; // 否则,记录这个值
}
}
// 如果没有找到重复的值,返回false
return false;
}
data () {
return {
form: {
quarantineProductDeclarationList: [],
},
rules: {
quarantineProductDeclarationList: {
detailList: {
countryRegion: [{ required: true, message: '请选择计划排放日期', trigger: 'blur' }, { validator: this.checkoutType }]
}
},
}
}
},
methods: {
checkoutType (rule, value, callback) {
// 先拿到detailList
const detailList = getObjectByPath(this.form, rule.field) || []
// 判断detailList里的countryRegion是否重复
if (hasDuplicateValueByKey(detailList, 'countryRegion')) {
callback("国家出现重复")
}
},
}