安裝axios和vuex
yarn add axios vuex@next
簡單封裝axios
- 在src目錄下新建utils文件夾
- utils文件夾下新建request.js
- request.js
import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
const service = axios.create({
baseURL: '/admin/', // url = base url + request url
timeout: 10000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
config.headers['Authorization'] = 'Bearer ' + getToken()
}
config.headers['Accept'] = 'application/json'
return config
},
error => {
// do something with request error
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code === 1) {
ElMessage({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000,
showClose: true
})
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
if (error.response && error.response.status !== 400 && error.response.status !== 401 && error.response.status !== 409) {
ElMessage({
message: error.response && error.response.data && error.response.data.message || error.message,
type: 'error',
duration: 5 * 1000,
showClose: true
})
}
if (error.response && error.response.status === 401) {
ElMessage({
message: '登錄已經(jīng)失效!',
type: 'error',
duration: 5 * 1000,
showClose: true
})
setTimeout(removeToken(), 2000)
setTimeout(router.push('/login'), 1000);
}
if (error.response && error.response.status === 400) {
ElMessage({
message: error.response.data.message,
type: 'error',
duration: 5 * 1000,
showClose: true
})
}
return Promise.reject(error)
}
)
export default service
狀態(tài)管理vuex
- 在src目錄下新建store文件夾
- store文件夾下新建index.js, getters.js,以及modules文件夾
- index.js
import { createStore } from 'vuex'
import getters from './getters'
// 導(dǎo)入模塊
const moduleFiles = import.meta.globEager('./modules/*.js')
var modules = {}
for (const path in moduleFiles) {
const moduleName = path.replace(/^\.\/(.*)\.\w+$/, '$1').split('/')[1]
modules[moduleName] = moduleFiles[path].default
}
export default createStore({
modules,
getters
})
- getters.js
const getters = {
token: (state) => state.user.token,
name: (state) => state.user.name,
avatar: (state) => state.user.avatar,
};
export default getters;
修改src/main.js,使用狀態(tài)管理
import { createApp } from "vue";
import App from "@/App.vue";
import router from "@/router";
import store from "@/store";
import installElementPlus from "@/plugins/element";
import "@/styles/index.scss";
const app = createApp(App);
installElementPlus(app);
app.use(router).use(store).mount("#app");
碼云地址: https://gitee.com/charming-cheng/vite-element-plus-admin
我的博客:https://www.charmingcheng.top/article/4.html