Nuxt3封裝useFetch請求并防止參數(shù)自動更新請求方式
前言
useFetch 可組合函數(shù)提供了一個方便的包裝器,用于useAsyncData和$fetch。
它會自動生成基于URL和fetch選項的鍵,根據(jù)服務器路由提供請求URL的類型提示,并推斷API響應類型。
useFetch,應該直接在設置函數(shù)、插件或路由中間件中調(diào)用。它返回響應式的可組合函數(shù),并處理將響應添加到Nuxt負載中,以便在頁面水合期間從服務器傳遞給客戶端而無需重新獲取數(shù)據(jù)。
注意:所有fetch選項都可以使用computed或ref值進行賦值。如果這些值更新,將自動進行新的請求。
以下請求封裝脫離了自動請求!!!
第一步 更改配置
1.配置環(huán)境變量
//.env.development NUXT_PUBLIC_API_BASE=http://localhost:8099/v1/api
//.env.production NUXT_PUBLIC_API_BASE=http://110.110.110.110:8099/v1/api
2.修改package.json配置
//package.json "dev": "nuxt dev --dotenv .env.development", "build": "nuxt build --dotenv .env.production",
3.修改nuxt.config.ts配置
//nuxt.config.ts
// 添加運行時配置
runtimeConfig: {
apiSecret: process.env.NUXT_API_SECRET,
public: {
apiBase: process.env.NUXT_PUBLIC_API_BASE || SERVER_BASE_API,
}
}
---------------------------------------------------------------------
// 如果存在跨域
nitro: {
devProxy: {
'/api': {
target: process.env.NUXT_PUBLIC_API_BASE,
changeOrigin: true,
}
}
}
第二步 請求封裝
1.在composables目錄下新建MyRequest.ts
_nuxt/composables/MyRequest.ts
//MyRequest.ts
import { ElMessage } from 'element-plus';
type UrlType = string | Request | Ref<string | Request> | (() => string | Request);
export interface RequestOptions {
method?: any;
params?: any;
}
const request = async (url: UrlType, params: any, options: RequestOptions) => {
const headers = useRequestHeaders(['cookie']);
const { apiBase: baseURL } = useRuntimeConfig().public;
const { method = ((options?.method || 'GET') as string).toUpperCase() } = options;
return await useFetch(url as string, {
default: () => [],
baseURL,
method,
params:{...params},//temp hook
headers,
// lazy: true,
credentials: 'include',
body: method === 'POST' ? JSON.stringify(params) : undefined,
onRequest({ request, options }) {
// Set the request headers
// options.headers = options.headers || {};
},
onRequestError({ request, options, error }) {
ElMessage.closeAll()
error && ElMessage.error('Sorry, The Data Request Failed');
// Handle the request errors
},
onResponse({ request, response, options }) {
// Process the response data
return response._data;
},
onResponseError({ request, response, options }) {
console.log('?? ~ file: MyRequest.ts:42 ~ onResponseError ~ request:', request);
// Handle the response errors
},
});
};
export const useDefaultRequest = {
get: (url: UrlType, params?: any, option?: RequestOptions) => {
return request(url, params, { method: 'GET', ...option });
},
post: (url: UrlType, params?: any, option?: RequestOptions) => {
return request(url, params, { method: 'POST', ...option });
},
};
2.API封裝
_nuxt/composables/Api.ts
export const useApiProductList = (params: any): any => {
return useDefaultRequest.get('/request', params);
};
export const useApiProductList = (params: any): any => {
return useDefaultRequest.get('/request1', params);
};
export const useApiProductList = (params: any): any => {
return useDefaultRequest.post('/request2', params);
};
第三步 使用
const { data: response } = useApiSetContact(inquiryForm);
type UseFetchOptions = {
key?: string
method?: string
query?: SearchParams
params?: SearchParams
body?: RequestInit['body'] | Record<string, any>
headers?: Record<string, string> | [key: string, value: string][] | Headers
baseURL?: string
server?: boolean
lazy?: boolean
immediate?: boolean
default?: () => DataT
transform?: (input: DataT) => DataT
pick?: string[]
watch?: WatchSource[]
}
type AsyncData<DataT, ErrorT> = {
data: Ref<DataT | null>
pending: Ref<boolean>
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
error: Ref<ErrorT | null>
}
- 官網(wǎng)API:https://nuxt.com/docs/api/composables/use-fetch
- 中文官網(wǎng):https://www.nuxt.com.cn/docs/api/composables/use-fetch
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3使用video-player實現(xiàn)視頻播放
video-player是一個基于video.js的視頻播放器組件,本文主要介紹了Vue3使用video-player實現(xiàn)視頻播放,具有一定的參考價值,感興趣的可以了解一下2024-01-01
利用vue組件自定義v-model實現(xiàn)一個Tab組件方法示例
這篇文章主要給大家介紹了關(guān)于利用vue組件自定義v-model實現(xiàn)一個Tab組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-12-12
Vue實現(xiàn)點擊按鈕下載文件的操作代碼(后端Java)
最近項目中需要實現(xiàn)點擊按鈕下載文件的需求,前端用的vue后端使用的java代碼,今天通過本文給大家分享vue點擊按鈕下載文件的實現(xiàn)代碼,需要的朋友參考下吧2021-08-08
Vue $attrs & inheritAttr實現(xiàn)button禁用效果案例
這篇文章主要介紹了Vue $attrs & inheritAttr實現(xiàn)button禁用效果案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12
詳解vuex數(shù)據(jù)傳輸?shù)膬煞N方式及this.$store undefined的解決辦法
這篇文章主要介紹了vuex數(shù)據(jù)傳輸?shù)膬煞N方式 及 this.$store undefined的解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08
詳解axios 全攻略之基本介紹與使用(GET 與 POST)
本篇文章主要介紹了axios 全攻略之基本介紹與使用(GET 與 POST),詳細的介紹了axios的安裝和使用,還有 GET 與 POST方法,有興趣的可以了解一下2017-09-09

