Vue|vue3+ts+axios请求封装使用
文章图片
请求封装
实际使用中可以根据项目修改,比如RESTful api中可以自行添加put和delete请求,ResType也可以根据后端的通用返回值动态的去修改
//http.ts
import axios from "axios"
import NProgress from "nprogress"
import type {
App } from "vue"
// const CancelToken = axios.CancelToken
// const source = CancelToken.source()// 设置请求头和请求路径
axios.defaults.baseURL = "/api"
axios.defaults.timeout = 10000
axios.defaults.headers.post["Content-Type"] = "application/json;
charset=UTF-8"
axios.interceptors.request.use(
(config) => {const token = window.sessionStorage.getItem("token")
if (token) {config.headers.token = token
}
return config
},
(error) => {return error
}
)
// 响应拦截
axios.interceptors.response.use((res) => {if (res.data.code === 111) {sessionStorage.setItem("token", "")
// token过期操作
}
return res
})interface ResType {code: number
data?: T
msg: string
err?: string
}
interface Http {get(url: string, params?: unknown): Promise>
post(url: string, params?: unknown): Promise>
upload(url: string, params: unknown): Promise>
download(url: string): void
}const http: Http = {get(url, params) {return new Promise((resolve, reject) => {NProgress.start()
axios
.get(url, {
params })
.then((res) => {NProgress.done()
resolve(res.data)
})
.catch((err) => {NProgress.done()
reject(err.data)
})
})
},
post(url, params) {return new Promise((resolve, reject) => {NProgress.start()
axios
.post(url, JSON.stringify(params))
.then((res) => {NProgress.done()
resolve(res.data)
})
.catch((err) => {NProgress.done()
reject(err.data)
})
})
},
upload(url, file) {return new Promise((resolve, reject) => {NProgress.start()
axios
.post(url, file, {headers: {
"Content-Type": "multipart/form-data" },
})
.then((res) => {NProgress.done()
resolve(res.data)
})
.catch((err) => {NProgress.done()
reject(err.data)
})
})
},
download(url) {const iframe = document.createElement("iframe")
iframe.style.display = "none"
iframe.src = https://www.it610.com/article/url
iframe.onload = function () {document.body.removeChild(iframe)
}
document.body.appendChild(iframe)
}
}
export default http
调用请求
【Vue|vue3+ts+axios请求封装使用】请求的时候需要在泛型中传入返回值data的类型,下面是一个示例请求调用
//login.ts
import http from "@/utils/http"
const res = await http.post<{
user: UserState;
token: string }>(
"/user/login",
formData
)
if (res.code === 1) {store.commit("user/setUser", res.data?.user)
sessionStorage.setItem("token", res.data?.token as string)
} else {ElMessage.error(res.msg)
}
推荐阅读
- vue-cli|vue-cli 3.x vue.config.js 配置
- 2020-04-07vue中Axios的封装和API接口的管理
- https请求被提早撤回
- VueX--VUE核心插件
- 遇到不正当请求怎么办
- vue组件中为何data必须是一个函数()
- 用npm发布一个包的教程并编写一个vue的插件发布
- vuex|vuex 基础结构
- Vue源码分析—响应式原理(二)
- VueX(Vuex|VueX(Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式)