這篇文章主要介紹了vite+vue3.0+ts中怎么封裝axios的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇vite+vue3.0+ts中怎么封裝axios文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。
我們提供的服務(wù)有:成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、臨沂ssl等。為1000+企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的臨沂網(wǎng)站制作公司
npm i axios
注意:這里的安裝命令就是默認(rèn)安裝最新版本的axios
代碼如下:
export const errorCodeType = function(code:string):string{ let errMessage:string = "未知錯(cuò)誤" switch (code) { case 400: errMessage = '錯(cuò)誤的請(qǐng)求' break case 401: errMessage = '未授權(quán),請(qǐng)重新登錄' break case 403: errMessage = '拒絕訪問(wèn)' break case 404: errMessage = '請(qǐng)求錯(cuò)誤,未找到該資源' break case 405: errMessage = '請(qǐng)求方法未允許' break case 408: errMessage = '請(qǐng)求超時(shí)' break case 500: errMessage = '服務(wù)器端出錯(cuò)' break case 501: errMessage = '網(wǎng)絡(luò)未實(shí)現(xiàn)' break case 502: errMessage = '網(wǎng)絡(luò)錯(cuò)誤' break case 503: errMessage = '服務(wù)不可用' break case 504: errMessage = '網(wǎng)絡(luò)超時(shí)' break case 505: errMessage = 'http版本不支持該請(qǐng)求' break default: errMessage = `其他連接錯(cuò)誤 --${code}` } return errMessage }
這里用到的element-plus大家可以參考其官網(wǎng)安裝即可,傳送門:
element-plus官網(wǎng)
安裝命令: npm install element-plus --save
代碼如下:
import axios from 'axios'; import { errorCodeType } from '@/script/utils/error-code-type'; import { ElMessage, ElLoading } from 'element-plus'; // 創(chuàng)建axios實(shí)例 const service = axios.create({ // 服務(wù)接口請(qǐng)求 baseURL: import.meta.env.VITE_APP_BASE_API, // 超時(shí)設(shè)置 // timeout: 15000, headers:{'Content-Type':'application/json;charset=utf-8'} }) let loading:any; //正在請(qǐng)求的數(shù)量 let requestCount:number = 0 //顯示loading const showLoading = () => { if (requestCount === 0 && !loading) { //加載中顯示樣式可以自行修改 loading = ElLoading.service({ text: "拼命加載中,請(qǐng)稍后...", background: 'rgba(0, 0, 0, 0.7)', spinner: 'el-icon-loading', }) } requestCount++; } //隱藏loading const hideLoading = () => { requestCount-- if (requestCount == 0) { loading.close() } } // 請(qǐng)求攔截 service.interceptors.request.use(config => { showLoading() // 是否需要設(shè)置 token放在請(qǐng)求頭 // config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改 // get請(qǐng)求映射params參數(shù) if (config.method === 'get' && config.params) { let url = config.url + '?'; for (const propName of Object.keys(config.params)) { const value = config.params[propName]; var part = encodeURIComponent(propName) + "="; if (value !== null && typeof(value) !== "undefined") { // 對(duì)象處理 if (typeof value === 'object') { for (const key of Object.keys(value)) { let params = propName + '[' + key + ']'; var subPart = encodeURIComponent(params) + "="; url += subPart + encodeURIComponent(value[key]) + "&"; } } else { url += part + encodeURIComponent(value) + "&"; } } } url = url.slice(0, -1); config.params = {}; config.url = url; } return config }, error => { console.log(error) Promise.reject(error) }) // 響應(yīng)攔截器 service.interceptors.response.use((res:any) => { hideLoading() // 未設(shè)置狀態(tài)碼則默認(rèn)成功狀態(tài) const code = res.data['code'] || 200; // 獲取錯(cuò)誤信息 const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default') if(code === 200){ return Promise.resolve(res.data) }else{ ElMessage.error(msg) return Promise.reject(res.data) } }, error => { console.log('err' + error) hideLoading() let { message } = error; if (message == "Network Error") { message = "后端接口連接異常"; } else if (message.includes("timeout")) { message = "系統(tǒng)接口請(qǐng)求超時(shí)"; } else if (message.includes("Request failed with status code")) { message = "系統(tǒng)接口" + message.substr(message.length - 3) + "異常"; } ElMessage.error({ message: message, duration: 5 * 1000 }) return Promise.reject(error) } ) export default service;
auto-imports.d.ts放在src目錄下
注意:需要安裝yarn add unplugin-auto-import或者npm i unplugin-auto-import -D
安裝完重啟項(xiàng)目
代碼如下:
declare global { const computed: typeof import('vue')['computed'] const createApp: typeof import('vue')['createApp'] const customRef: typeof import('vue')['customRef'] const defineAsyncComponent: typeof import('vue')['defineAsyncComponent'] const defineComponent: typeof import('vue')['defineComponent'] const effectScope: typeof import('vue')['effectScope'] const EffectScope: typeof import('vue')['EffectScope'] const getCurrentInstance: typeof import('vue')['getCurrentInstance'] const getCurrentScope: typeof import('vue')['getCurrentScope'] const h: typeof import('vue')['h'] const inject: typeof import('vue')['inject'] const isReadonly: typeof import('vue')['isReadonly'] const isRef: typeof import('vue')['isRef'] const markRaw: typeof import('vue')['markRaw'] const nextTick: typeof import('vue')['nextTick'] const onActivated: typeof import('vue')['onActivated'] const onBeforeMount: typeof import('vue')['onBeforeMount'] const onBeforeUnmount: typeof import('vue')['onBeforeUnmount'] const onBeforeUpdate: typeof import('vue')['onBeforeUpdate'] const onDeactivated: typeof import('vue')['onDeactivated'] const onErrorCaptured: typeof import('vue')['onErrorCaptured'] const onMounted: typeof import('vue')['onMounted'] const onRenderTracked: typeof import('vue')['onRenderTracked'] const onRenderTriggered: typeof import('vue')['onRenderTriggered'] const onScopeDispose: typeof import('vue')['onScopeDispose'] const onServerPrefetch: typeof import('vue')['onServerPrefetch'] const onUnmounted: typeof import('vue')['onUnmounted'] const onUpdated: typeof import('vue')['onUpdated'] const provide: typeof import('vue')['provide'] const reactive: typeof import('vue')['reactive'] const readonly: typeof import('vue')['readonly'] const ref: typeof import('vue')['ref'] const resolveComponent: typeof import('vue')['resolveComponent'] const shallowReactive: typeof import('vue')['shallowReactive'] const shallowReadonly: typeof import('vue')['shallowReadonly'] const shallowRef: typeof import('vue')['shallowRef'] const toRaw: typeof import('vue')['toRaw'] const toRef: typeof import('vue')['toRef'] const toRefs: typeof import('vue')['toRefs'] const triggerRef: typeof import('vue')['triggerRef'] const unref: typeof import('vue')['unref'] const useAttrs: typeof import('vue')['useAttrs'] const useCssModule: typeof import('vue')['useCssModule'] const useCssVars: typeof import('vue')['useCssVars'] const useSlots: typeof import('vue')['useSlots'] const watch: typeof import('vue')['watch'] const watchEffect: typeof import('vue')['watchEffect'] } export {}
注意:需要安裝npm i unplugin-vue-components -D或者yarn add unplugin-vue-components
安裝完重啟項(xiàng)目
import '@vue/runtime-core' declare module '@vue/runtime-core' { export interface GlobalComponents { ElCard: typeof import('element-plus/es')['ElCard'] ElCol: typeof import('element-plus/es')['ElCol'] ElContainer: typeof import('element-plus/es')['ElContainer'] ElFooter: typeof import('element-plus/es')['ElFooter'] ElHeader: typeof import('element-plus/es')['ElHeader'] ElMain: typeof import('element-plus/es')['ElMain'] ElOption: typeof import('element-plus/es')['ElOption'] ElPagination: typeof import('element-plus/es')['ElPagination'] ElRadioButton: typeof import('element-plus/es')['ElRadioButton'] ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup'] ElRow: typeof import('element-plus/es')['ElRow'] ElSelect: typeof import('element-plus/es')['ElSelect'] ElTable: typeof import('element-plus/es')['ElTable'] ElTableColumn: typeof import('element-plus/es')['ElTableColumn'] Loading: typeof import('element-plus/es')['ElLoadingDirective'] } } export {}
注意:需要安裝npm i unplugin-icons或者yarn add unplugin-icons
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import Icons from "unplugin-icons/vite"; import IconsResolver from "unplugin-icons/resolver"; import AutoImport from "unplugin-auto-import/vite"; import Components from "unplugin-vue-components/vite"; import { ElementPlusResolver } from "unplugin-vue-components/resolvers"; import { loadEnv } from 'vite'; import path from 'path'; // 路徑 const pathSrc = path.resolve(__dirname,'src') // https://vitejs.dev/config/ export default({ command, mode }) => { return defineConfig({ plugins: [ vue(), AutoImport({ // Auto import functions from Vue, e.g. ref, reactive, toRef... // 自動(dòng)導(dǎo)入 Vue 相關(guān)函數(shù),如:ref, reactive, toRef 等 imports: ["vue"], // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style) // 自動(dòng)導(dǎo)入 Element Plus 相關(guān)函數(shù),如:ElMessage, ElMessageBox... (帶樣式) resolvers: [ ElementPlusResolver(), // Auto import icon components // 自動(dòng)導(dǎo)入圖標(biāo)組件 IconsResolver({ prefix: "Icon", }), ], dts: path.resolve(pathSrc, "auto-imports.d.ts"), }), // 自動(dòng)導(dǎo)入 Element Plus 組件 Components({ resolvers: [ // Auto register icon components // 自動(dòng)注冊(cè)圖標(biāo)組件 IconsResolver({ enabledCollections: ["ep"], }), // Auto register Element Plus components ElementPlusResolver(), ], dts: path.resolve(pathSrc, "components.d.ts"), }), // 圖標(biāo) Icons({ autoInstall: true, }), ], server:{ host: '127.0.0.1', //port: Number(loadEnv(mode, process.cwd()).VITE_APP_PORT), port: 3000, strictPort: true, // 端口被占用直接退出 https: false, open: true,// 在開發(fā)服務(wù)器啟動(dòng)時(shí)自動(dòng)在瀏覽器中打開應(yīng)用程序 proxy: { // 字符串簡(jiǎn)寫寫法 '^/api': { target: mode==='development'?loadEnv(mode, process.cwd()).VITE_APP_DEV_URL:loadEnv(mode, process.cwd()).VITE_APP_PROD_URL, changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } }, hmr:{ overlay: false // 屏蔽服務(wù)器報(bào)錯(cuò) } }, resolve:{ alias:{ '@': pathSrc, } }, css:{ // css預(yù)處理器 /*preprocessorOptions: { scss: { additionalData: '@import "@/assets/styles/global.scss";' } }*/ preprocessorOptions: { less: { charset: false, additionalData: '@import "./src/assets/style/global.less";', }, }, }, build:{ chunkSizeWarningLimit: 1500, // 分塊打包,分解塊,將大塊分解成更小的塊 rollupOptions: { output:{ manualChunks(id) { if (id.includes('node_modules')) { return id.toString().split('node_modules/')[1].split('/')[0].toString(); } } } } } }) }
完整的環(huán)境變量配置文件.env.production和.env.development
7.1、項(xiàng)目根目錄的development文件內(nèi)容如下
# 開發(fā)環(huán)境 VITE_APP_TITLE = "阿綿" # 端口號(hào) VITE_APP_PORT = "3000" # 請(qǐng)求接口 VITE_APP_DEV_URL = "http://localhost:8088" # 前綴 VITE_APP_BASE_API = "/api"
7.2、項(xiàng)目根目錄下的production文件內(nèi)容如下
# 開發(fā)環(huán)境 VITE_APP_TITLE = "阿綿" # 端口號(hào) VITE_APP_PORT = "3000" # 請(qǐng)求接口 VITE_APP_DEV_URL = "http://localhost:8088" # 前綴 VITE_APP_BASE_API = "/api"
注意:這里還有一個(gè)PageParams全局分頁(yè)對(duì)象:
page-params.ts
代碼如下:
// 全局統(tǒng)一分頁(yè)參數(shù)類型聲明 declare interface PageParams { pageNum: number, pageSize: number, type?: Model, // 可選參數(shù) readonly sort?: string // 只讀可選參數(shù) } interface Model { type?: string } export default PageParams;
關(guān)于“vite+vue3.0+ts中怎么封裝axios”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“vite+vue3.0+ts中怎么封裝axios”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱:vite+vue3.0+ts中怎么封裝axios
當(dāng)前URL:http://m.newbst.com/article46/jeishg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、網(wǎng)站設(shè)計(jì)公司、網(wǎng)頁(yè)設(shè)計(jì)公司、動(dòng)態(tài)網(wǎng)站、全網(wǎng)營(yíng)銷推廣、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)