项目中封装接口请求,并且解决刷新页面useFetch无返回数据问题
刷新页面useFetch无返回数据问题:

浏览器刷新的时候页面没有显示数据,接口data无返回。本身nuxt的useFetch在参数不变的情况下,数据是不会重新从后台接口去请求数据的,会直接拿上一次的结果。但是有实时去后台获取数据这样的需求,
比如我的关注页面,在其他页面点了关注,每次进这个页面或者刷新都需要去后台重新获取数据,所以我给入参加了一个以时间戳为值的参数key,但是这样导致每次F5刷新页面的时候,都拿不到数据,导致页面没有显示。Suspense不起作用。

utils/https.ts

import { _AsyncData } from "nuxt3/dist/app/composables/asyncData";import { ElMessage } from "element-plus";const baseUrl = "";// 指定后端返回的基本数据类型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("执行错误了");// 这里处理错误回调// 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接口放在这个里面会自动导入函数

import Http from "@/utils/http";/** * 测试接口 */export const getTags = () => {return Http.get("https://api/apiWx/wechat-config");};

在页面或者组件中使用:

onMounted(() => { getTags() .then((res) => { console.log(res.value.data, "res"); }) .catch((err) => {console.log(err, "错误"); });});