三、axios,API和路由封装
3.1 axios二次封装
pnpm i axios
在src下建立如图文件夹
在request下配置请求拦截器,响应拦截器
import axios from 'axios'
import { ElMessage } from 'element-plus'let request = axios.create({baseURL: import.meta.env.VITE_SERVE,timeout: 5 * 1000,
})request.interceptors.request.use((config) => {return config
})request.interceptors.response.use((response) => {return response.data},(error) => {let message = ''let status = error.response.statusswitch (status) {case 401:message = 'TOKEN过期'breakcase 403:message = '无权访问'breakcase 404:message = '请求地址错误'breakcase 500:message = '服务器出现问题'breakdefault:message = '网络出现问题'break}ElMessage({type: 'error',message,})return Promise.reject(error)},
)export default request
3.2API统一管理
这里是登录api举例,src建立如下文件夹
首先是index.ts
import request from '@/utils/request'
import type { loginForm, loginResponseData, userInfoData } from './type'enum API {LOGIN_URL = 'user/login',USERINFO_URL = 'user/info',
}//登录接口方法
export const login = (data: loginForm) =>request.post<any, loginResponseData>(API.LOGIN_URL, data)//获取用户信息
export const userInfo = () => request.get<any, userInfoData>(API.USERINFO_URL)
其次是type.ts
//登录接口需要携带参数的ts类型
export interface loginForm {username: stringpassword: string
}//登录返回的参数类型
export interface loginResponseData {code: numbermessage: stringdata: string
}//返回的userInfo类型
export interface userInfoData {code: numbermessage: stringdata: {id: stringroleNames: string[]avatar: stringname: string}
}
3.3router配置
src建立如图文件夹
pnpm i vue-router
在index.ts
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'let router = createRouter({history: createWebHashHistory(),routes: constantRoute,
})export default router
routes.ts下,登录,404,home配置相似
export const constantRoute: Array<RouteRecordRaw> = [{path: '/login',name: 'login',component: () => import('@/views/login/index.vue'),meta: {title: '登录',hidden: true,},},// 404{path: '/404',name: '404',component: () => import('@/views/404/index.vue'),meta: {title: '404',hidden: true,},},{path: '/:pathMatch(.*)*',redirect: '/404',name: 'Any',meta: {title: '任意路由',hidden: true,},},
]
main.ts引入路由
//引入路由
import router from './router'
注册路由
//注册路由
app.use(router)
App.vue文件
<template><router-view></router-view>
</template><script setup lang="ts">
</script><style lang="scss" scoped></style>