企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # ts 泛型配合接口 ~~~ 1.简单的配合泛型去做解决思路 ~~~ >[danger] ##### 案例 * 在请求hook 文件下的 ~~~ import axios from 'axios' import { reactive, ref, toRefs } from 'vue' function userURLLoader<T> (url: string){ // const res = ref(null) // const loading = ref(true) // const loaded = ref(false) // const error = ref(null) // axios.get(url).then((rs)=>{ // loading.value =false // res.value =rs.data // loaded.value = true // }).catch((e)=>{ // error.value = e // }) // return { res,loaded,loading,error} // 需要定义变量 const res:{error:any,loaded:boolean,loading:boolean,data:T|null} = reactive({ error:null, loading:true, loaded:false, data:null }) axios.get(url).then((resData)=>{ res.loaded = true res.loading = false res.data = resData.data }).catch((e)=>{ res.error = e }) return { ...toRefs(res) } } export default userURLLoader ~~~ * 使用 ~~~ <template> <div class="about"> <h1 v-if="loading">Loading!...</h1> <img v-if="loaded" :src="data.message" > </div> </template> <script lang="ts"> interface DogResult { message: string; status: string; } import userURLLoader from '../hook/userURLLoader' export default { setup(){ const {data,loaded,loading,error} = userURLLoader<DogResult>('https://dog.ceo/api/breeds/image/random') return { data,loaded,loading,error } } } </script> ~~~