jdcProject_front/src/hooks/useFetchSelect.ts

54 lines
989 B
TypeScript
Raw Normal View History

import { ref, onMounted } from "vue"
2023-01-05 17:15:18 +08:00
type OptionValueType = string | number
/** Select 需要的数据格式 */
interface ISelectOption {
value: OptionValueType
2023-01-05 17:15:18 +08:00
label: string
disabled?: boolean
}
/** 接口响应格式 */
interface IApiData {
code: number
data: ISelectOption[]
message: string
2023-01-05 17:15:18 +08:00
}
/** 入参格式,暂时只需要传递 api 函数即可 */
interface IFetchSelectProps {
api: () => Promise<IApiData>
}
2023-01-05 17:15:18 +08:00
export function useFetchSelect(props: IFetchSelectProps) {
const { api } = props
2023-01-05 17:15:18 +08:00
const loading = ref<boolean>(false)
const options = ref<ISelectOption[]>([])
const value = ref<OptionValueType>("")
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
}
}