Nuxt3封裝useFetch請(qǐng)求并防止參數(shù)自動(dòng)更新請(qǐng)求方式
前言
useFetch 可組合函數(shù)提供了一個(gè)方便的包裝器,用于useAsyncData和$fetch。
它會(huì)自動(dòng)生成基于URL和fetch選項(xiàng)的鍵,根據(jù)服務(wù)器路由提供請(qǐng)求URL的類型提示,并推斷API響應(yīng)類型。
useFetch,應(yīng)該直接在設(shè)置函數(shù)、插件或路由中間件中調(diào)用。它返回響應(yīng)式的可組合函數(shù),并處理將響應(yīng)添加到Nuxt負(fù)載中,以便在頁(yè)面水合期間從服務(wù)器傳遞給客戶端而無(wú)需重新獲取數(shù)據(jù)。
注意:所有fetch選項(xiàng)都可以使用computed或ref值進(jìn)行賦值。如果這些值更新,將自動(dòng)進(jìn)行新的請(qǐng)求。
以下請(qǐng)求封裝脫離了自動(dòng)請(qǐng)求!!!
第一步 更改配置
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
// 添加運(yùn)行時(shí)配置
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,
}
}
}
第二步 請(qǐng)求封裝
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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3使用video-player實(shí)現(xiàn)視頻播放
video-player是一個(gè)基于video.js的視頻播放器組件,本文主要介紹了Vue3使用video-player實(shí)現(xiàn)視頻播放,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
利用vue組件自定義v-model實(shí)現(xiàn)一個(gè)Tab組件方法示例
這篇文章主要給大家介紹了關(guān)于利用vue組件自定義v-model實(shí)現(xiàn)一個(gè)Tab組件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
Vue3.0?axios跨域請(qǐng)求代理服務(wù)器配置方式
這篇文章主要介紹了Vue3.0?axios跨域請(qǐng)求代理服務(wù)器配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue實(shí)現(xiàn)點(diǎn)擊按鈕下載文件的操作代碼(后端Java)
最近項(xiàng)目中需要實(shí)現(xiàn)點(diǎn)擊按鈕下載文件的需求,前端用的vue后端使用的java代碼,今天通過(guò)本文給大家分享vue點(diǎn)擊按鈕下載文件的實(shí)現(xiàn)代碼,需要的朋友參考下吧2021-08-08
Vue $attrs & inheritAttr實(shí)現(xiàn)button禁用效果案例
這篇文章主要介紹了Vue $attrs & inheritAttr實(shí)現(xiàn)button禁用效果案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
詳解vuex數(shù)據(jù)傳輸?shù)膬煞N方式及this.$store undefined的解決辦法
這篇文章主要介紹了vuex數(shù)據(jù)傳輸?shù)膬煞N方式 及 this.$store undefined的解決辦法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
詳解axios 全攻略之基本介紹與使用(GET 與 POST)
本篇文章主要介紹了axios 全攻略之基本介紹與使用(GET 與 POST),詳細(xì)的介紹了axios的安裝和使用,還有 GET 與 POST方法,有興趣的可以了解一下2017-09-09

