項(xiàng)目中封裝接口請(qǐng)求,并且解決刷新頁面useFetch無返回?cái)?shù)據(jù)問題
刷新頁面useFetch無返回?cái)?shù)據(jù)問題:
瀏覽器刷新的時(shí)候頁面沒有顯示數(shù)據(jù),接口data無返回。本身nuxt的useFetch在參數(shù)不變的情況下,數(shù)據(jù)是不會(huì)重新從后臺(tái)接口去請(qǐng)求數(shù)據(jù)的,會(huì)直接拿上一次的結(jié)果。但是有實(shí)時(shí)去后臺(tái)獲取數(shù)據(jù)這樣的需求,
比如我的關(guān)注頁面,在其他頁面點(diǎn)了關(guān)注,每次進(jìn)這個(gè)頁面或者刷新都需要去后臺(tái)重新獲取數(shù)據(jù),所以我給入?yún)⒓恿艘粋€(gè)以時(shí)間戳為值的參數(shù)key,但是這樣導(dǎo)致每次F5刷新頁面的時(shí)候,都拿不到數(shù)據(jù),導(dǎo)致頁面沒有顯示。Suspense不起作用。
utils/https.ts
import { _AsyncData } from "nuxt3/dist/app/composables/asyncData";
import { ElMessage } from "element-plus";
const baseUrl = "";
// 指定后端返回的基本數(shù)據(jù)類型
export interface ResponseConfig {
code: number;
status: number;
data: any;
msg: string;
}
export interface ValueConfig {
value: any;
}
const fetch = async (url: string, options?: any): Promise<any> => {
await nextTick(); //解決刷新頁面useFetch無返回
const reqUrl = baseUrl + url;
return new Promise((resolve, reject) => {
useFetch(reqUrl, { ...options })
.then(({ data, error }: _AsyncData) => {
if (error.value) {
reject(error.value);
return;
}
const value = data.value;
if (!value) {
console.log("執(zhí)行錯(cuò)誤了");
// 這里處理錯(cuò)誤回調(diào)
// reject(value)
// $router.replace('/reject/' + value.status)
} else if (value.code === 102) {
ElMessage({
message: value.msg,
type: "error",
});
} else {
resolve(ref(value));
}
})
.catch((err: any) => {
reject(err);
});
});
};
export default new (class Http {
get(url: string, params?: any): Promise<any> {
return fetch(url, { method: "get", params });
}
post(url: string, params?: any): Promise<any> {
return fetch(url, { method: "post", params });
}
put(url: string, body?: any): Promise<any> {
return fetch(url, { method: "put", body });
}
delete(url: string, body?: any): Promise<any> {
return fetch(url, { method: "delete", body });
}
})();
使用方法:composables/index.ts,api接口放在這個(gè)里面會(huì)自動(dòng)導(dǎo)入函數(shù)文章來源:http://www.zghlxwxcb.cn/news/detail-505959.html
import Http from "@/utils/http";
/**
* 測(cè)試接口
*/
export const getTags = () => {
return Http.get("https://api/apiWx/wechat-config");
};
在頁面或者組件中使用:文章來源地址http://www.zghlxwxcb.cn/news/detail-505959.html
onMounted(() => {
getTags()
.then((res) => {
console.log(res.value.data, "res");
})
.catch((err) => {
console.log(err, "錯(cuò)誤");
});
});
到了這里,關(guān)于nuxt3 useFetch封裝一個(gè)api接口http請(qǐng)求 - 解決刷新頁面useFetch無返回的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!