jdcProject_front/src/hooks/useFetchSelect.ts

54 lines
970 B
TypeScript
Raw Normal View History

import { ref, onMounted } from "vue"
2023-01-05 17:15:18 +08:00
type OptionValue = string | number
/** Select 需要的数据格式 */
interface SelectOption {
value: OptionValue
2023-01-05 17:15:18 +08:00
label: string
disabled?: boolean
}
/** 接口响应格式 */
interface ApiData {
code: number
data: SelectOption[]
message: string
2023-01-05 17:15:18 +08:00
}
/** 入参格式,暂时只需要传递 api 函数即可 */
interface FetchSelectProps {
api: () => Promise<ApiData>
}
2023-01-05 17:15:18 +08:00
export function useFetchSelect(props: FetchSelectProps) {
const { api } = props
2023-01-05 17:15:18 +08:00
const loading = ref<boolean>(false)
const options = ref<SelectOption[]>([])
const value = ref<OptionValue>("")
2023-01-05 17:15:18 +08:00
/** 调用接口获取数据 */
2023-01-05 17:15:18 +08:00
const loadData = () => {
loading.value = true
options.value = []
api()
.then((res) => {
2023-01-05 17:15:18 +08:00
options.value = res.data
})
.finally(() => {
2023-01-05 17:15:18 +08:00
loading.value = false
})
2023-01-05 17:15:18 +08:00
}
onMounted(() => {
loadData()
})
return {
loading,
options,
value
2023-01-05 17:15:18 +08:00
}
}