新建一个index.ts
/**
* 封装axios 添加loading
*/
import router from '@/router'
import axios, { AxiosError, type AxiosRequestConfig } from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
export const httpInstance = axios.create()
export type BKResponse = {
data: any
message: string
success: true
code: number
}
//设置请求根路径
httpInstance.defaults.baseURL = import.meta.env.VITE_BASEURL
//设置相应
export const $http = async (config: AxiosRequestConfig) => {
const loadingInstance = ElLoading.service()
try {
const axiosResponse = await httpInstance<BKResponse>(config)
const res = await axiosResponse.data
if (!res?.success) {
let erTitle: string = 'Error'
if (res.code === 401) {
erTitle = 'Unauthorized'
ElMessage.error('未授权')
//跳转到首页
router.push('/login')
} else if (res.code === 403) {
erTitle = 'Forbidden'
ElMessage.error('禁止访问')
} else if (res.code === 999) {
erTitle = 'error'
ElMessage.error('后端自定义')
} else if (res.code === 500) {
erTitle = 'ServeError'
ElMessage.error('服务异常')
} else {
erTitle = 'Unknow'
}
//抛出其他或者为止异常
const error = new Error(res?.message || 'Unknow')
error.name = erTitle
throw error
}
return res
} catch (err) {
if (err instanceof AxiosError) {
ElMessage.error('网络错误')
}
throw err
} finally {
loadingInstance.close()
}
}
同级目录新建login.ts
import { $http } from './index'
type loginParams = {
username: string
password: string
}
export const loginApi = (data: loginParams) => {
return $http({
method: 'POST',
url: '/LOGIN',
data: data
})
}
页面引入
<script setup lang="ts">
import { ref } from 'vue'
import { loginApi } from '@/apis/login'
const form = ref({
username: 'admin',
password: '123456'
})
const login = async () => {
const res = await loginApi(form.value)
console.log(res)
}
console.log(login)
</script>
<template>login</template>
<style scoped></style>