u
This commit is contained in:
1 parent
985b42cafb
commit
5e3dccc88b
25 files changed
+931
-543
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import type { Ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export interface UseSelectableProps<T> {
|
||||
modelValue: T[]
|
||||
multiple?: boolean
|
||||
options?: Record<string, any>[]
|
||||
valueField?: string
|
||||
}
|
||||
|
||||
export function useSelectable<T>(
|
||||
props: UseSelectableProps<T>,
|
||||
onChange?: (selectedValues: T[], selectedOptions?: Record<string, any>[]) => void,
|
||||
) {
|
||||
const valueField = props.valueField || 'value'
|
||||
|
||||
// 修复:使用泛型参数明确指定 ref 的类型
|
||||
const selectedValues = ref<T[]>(props.modelValue) as Ref<T[]>
|
||||
|
||||
const updateValue = (option: Record<string, any>, checked: boolean) => {
|
||||
const val = option[valueField] as T
|
||||
|
||||
let newValues: T[]
|
||||
if (props.multiple) {
|
||||
newValues = checked
|
||||
? selectedValues.value.includes(val)
|
||||
? [...selectedValues.value]
|
||||
: [...selectedValues.value, val]
|
||||
: selectedValues.value.filter(v => v !== val)
|
||||
}
|
||||
else {
|
||||
newValues = checked ? [val] : []
|
||||
}
|
||||
|
||||
selectedValues.value = newValues
|
||||
|
||||
// 如果有 options,返回完整对象数组
|
||||
const selectedOptions = props.options?.filter(opt => newValues.includes(opt[valueField]))
|
||||
|
||||
onChange?.(newValues, selectedOptions)
|
||||
}
|
||||
|
||||
return {
|
||||
selectedValues,
|
||||
updateValue,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user