Vue3中使用typescript封装axios的实例详解
短信预约 -IT技能 免费直播动态提醒
这个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: AxiosRequestConfig) => {
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 => {
loading.close()
return Promise.reject(error) // 为了可以在代码中catch到错误信息
})
this.service.interceptors.response.use((response: AxiosResponse<any>) => {
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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341