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.data3. 请求头加上token,结合vuex或localstorage:if(store.getters.token) config.headers['x-token'] = store.getters.tokenelse 重定向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) => {/* 1. 关闭全屏loading动画2. 数据解密3. 根据 response.data.code 做不同的错误处理4. ……*/loading.close()const data = https://www.it610.com/article/response.dataconst { code } = dataif (code !=='000000') {ElMessage.error(data.message)return Promise.reject(data)}return response.data}, error => {loading.close()ElMessage.error('请求失败',)return Promise.reject(error)})}get(url: string, params?: object, _object = {}): Promise > {return this.service.get(url, { params, ..._object })}post (url: string, params?: object, _object = {}): Promise > {return this.service.post(url, params, _object)}put (url: string, params?: object, _object = {}): Promise > {return this.service.put(url, params, _object)}delete (url: string, params?: any, _object = {}): Promise > {return this.service.delete(url, { params, ..._object })}}export default new Http(config)
【Vue3中使用typescript封装axios的实例详解】types/index.ts: 接口返回数据的类型定义
export interface IResponseData{status: number; message?:string; data:T; code: string; }
axios的使用
list.vue:
const { data } = await http.get
//- 查询formel-form(:inline="true" :model="queryForm" size="small" label-position="left")el-form-itemel-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-itemel-button(type="primary" @click="query")| 查询//- 列表el-table(:data="https://www.it610.com/article/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-itemel-button(type="primary" size="small" @click="submit")| 确定
types/goods.ts
export interface IGoodInfo {_id: string; goodName: string; count: string; des: string}export interface IList {list: IGoodInfo[]}
到此这篇关于使用typescript封装axios的文章就介绍到这了,更多相关typescript封装axios内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 热闹中的孤独
- Shell-Bash变量与运算符
- JS中的各种宽高度定义及其应用
- 2021-02-17|2021-02-17 小儿按摩膻中穴-舒缓咳嗽
- 深入理解Go之generate
- 由浅入深理解AOP
- 异地恋中,逐渐适应一个人到底意味着什么()
- 【译】20个更有效地使用谷歌搜索的技巧
- 我眼中的佛系经纪人
- 《魔法科高中的劣等生》第26卷(Invasion篇)发售