Vue3中使用typescript封裝axios的實例詳解
這個axios封裝,因為是用在vue3的demo裡面的,為瞭方便,在vue3的配置裡面按需加載element-plus
封裝axios
http.ts
import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios' import { IResponseData } from '@/types' import { ElMessage, ElLoading, ILoadingInstance } from 'element-plus' type TAxiosOption = { baseURL: string; timeout: number; } const config = { baseURL: '/', timeout: 120000 } let loading: ILoadingInstance; class Http { // service: AxiosInstance; service; constructor(config: TAxiosOption) { this.service = axios.create(config) /* 請求攔截 this.service.interceptors.request.use(config => config, error => Promise.reject(error))*/ this.service.interceptors.request.use((config: AxiosRequestConfig) => { /* 業務邏輯 1. 開啟全屏loading動畫 2. 數據加密config.data 3. 請求頭加上token,結合vuex或localstorage: if(store.getters.token) config.headers['x-token'] = store.getters.token else 重定向 4. …… */ loading = ElLoading.service({ lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(255, 255, 255, 0.7)', }) if (localStorage.getItem('token')) { (config.headers as AxiosRequestHeaders).authorization = localStorage.getItem('token') as string } return config }, error => { /* 請求錯誤 1. 關閉全屏loading動畫 2. 重定向到錯誤頁 */ loading.close() return Promise.reject(error) // 為瞭可以在代碼中catch到錯誤信息 }) /* 響應攔截 this.service.interceptors.response.use(response => response.data, error => Promise.reject(error))*/ this.service.interceptors.response.use((response: AxiosResponse<any>) => { /* 1. 關閉全屏loading動畫 2. 數據解密 3. 根據 response.data.code 做不同的錯誤處理 4. …… */ loading.close() const data = response.data const { code } = data if (code !== '000000') { ElMessage.error(data.message) return Promise.reject(data) } return response.data }, error => { loading.close() ElMessage.error('請求失敗',) return Promise.reject(error) }) } get<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.get(url, { params, ..._object }) } post<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.post(url, params, _object) } put<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.put(url, params, _object) } delete<T>(url: string, params?: any, _object = {}): Promise<IResponseData<T>> { return this.service.delete(url, { params, ..._object }) } } export default new Http(config)
types/index.ts: 接口返回數據的類型定義
export interface IResponseData<T> { status: number; message?:string; data:T; code: string; }
axios的使用
list.vue:
const { data } = await http.get<IList>(‘/goods/list’, queryForm.value) list.value = data.list
<template lang="pug"> //- 查詢form el-form(:inline="true" :model="queryForm" size="small" label-position="left") el-form-item el-button(type="primary" @click="operate") | 新增 el-form-item(label="商品編號") el-input(v-model="queryForm._id") el-form-item(label="商品名") el-input(v-model="queryForm.goodName") el-form-item(label="數量") el-input(v-model="queryForm.count") el-form-item(label="詳情") el-input(v-model="queryForm.des") el-form-item el-button(type="primary" @click="query") | 查詢 //- 列表 el-table(:data="list" center size="mini") el-table-column(prop="goodName" label="商品名") el-table-column(prop="count" label="數量") el-table-column(prop="des" label="詳情") el-table-column(label="操作") template(#default="props") el-button(type="primary" size="small" @click="operate(props.row)") | 編輯 el-button(type="danger" size="small" @click="operate(props.row, true)") | 刪除 //- 新增、編輯 el-drawer(v-model="detailShow" :title="editShow === true ? '編輯' : '新增'" direction="rtl") el-form(:model="detailForm" size="small" label-width="80px" label-position="left") //- el-form-item(label="商品編號" required v-if="false") el-form-item(label="商品編號" required v-if="log(editShow)") el-input(v-model="detailForm._id" readonly) el-form-item(label="商品名" required) el-input(v-model="detailForm.goodName") el-form-item(label="數量") el-input(v-model="detailForm.count") el-form-item(label="詳情") el-input(v-model="detailForm.des") el-form-item el-button(type="primary" size="small" @click="submit") | 確定 </template> <script lang="ts"> import { defineComponent, reactive, ref } from 'vue'; import { ElMessage } from 'element-plus' import { IGoodInfo, IList } from '@/types/goods' import http from '@/http' export default defineComponent({ name: 'Home', setup() { const list = ref<IGoodInfo[]>([]) const queryForm = ref({ goodName: '', count: '', _id: '', des: '' }) const detailForm = ref({ goodName: '', count: '', _id: '', des: '' }) const detailShow = ref(false) const editShow = ref(false) query() async function query() { const { data } = await http.get<IList>('/goods/list', queryForm.value) list.value = data.list } async function operate(form?: IGoodInfo, flag?: true) { if (!form) { detailShow.value = true editShow.value = false detailForm.value = { goodName: '', count: '', _id: '', des: '' } } else if (!flag) { detailShow.value = true editShow.value = true detailForm.value = { ...form } } else { await http.delete('/goods/delete', { _id: form._id }) query() } } async function submit() { if (detailForm.value._id) { await http.put('/goods/edit', detailForm.value) }else{ await http.put('/goods/edit', detailForm.value) } detailShow.value = false ElMessage({ message: '操作成功', type: 'success', }) query() } function log(params:any) { console.log(params); return params } return { detailShow, editShow, list, queryForm, detailForm, query, operate, submit, log } } }); </script>
types/goods.ts
export interface IGoodInfo { _id: string; goodName: string; count: string; des: string } export interface IList { list: IGoodInfo[] }
到此這篇關於使用typescript封裝axios的文章就介紹到這瞭,更多相關typescript封裝axios內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 前端vue2 element ui高效配置化省時又省力
- Vue項目中封裝axios的方法
- react中axios結合後端實現GET和POST請求方式
- vue中axios封裝使用的完整教程
- vue封裝axios的幾種方法