辅助条码单位重复选择校验并提示
This commit is contained in:
1 parent
f1669fb843
commit
bd0e9c3dd2
2 files changed
+55
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { Ref, ref, watchEffect } from "vue"
|
||||
|
||||
const useUniqueField = <T>(items: Ref<T[]>, field: Ref<keyof T> | string) => {
|
||||
const isUnique = ref(true)
|
||||
const errorMessage = ref("")
|
||||
|
||||
watchEffect(() => {
|
||||
try {
|
||||
const seen = new Set()
|
||||
isUnique.value = true
|
||||
errorMessage.value = ""
|
||||
|
||||
// 处理非响应式的字段名
|
||||
const fieldKey = typeof field === "object" ? field.value : field
|
||||
|
||||
for (const item of items.value) {
|
||||
const value = item[fieldKey as keyof T]
|
||||
|
||||
// 处理 undefined/null 的特殊情况
|
||||
const key = value === null ? "NULL" : value === undefined ? "UNDEFINED" : value
|
||||
|
||||
if (seen.has(key)) {
|
||||
isUnique.value = false
|
||||
errorMessage.value = `字段 "${String(fieldKey)}" 存在重复值`
|
||||
break
|
||||
}
|
||||
seen.add(key)
|
||||
}
|
||||
} catch (error: any) {
|
||||
errorMessage.value = `验证失败: ${error.message}`
|
||||
}
|
||||
})
|
||||
|
||||
return { isUnique, errorMessage }
|
||||
}
|
||||
|
||||
export default useUniqueField
|
||||
Reference in new issue
Block a user