fix: logout

This commit is contained in:
张传龙 2022-09-21 17:14:41 +08:00
parent 4a5b8dd005
commit 85a04fd06d
7 changed files with 91 additions and 56 deletions

View File

@ -1,22 +1,30 @@
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router' import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import { setupRouterGuard } from './guard' import { setupRouterGuard } from './guard'
import { basicRoutes as routes, EMPTY_ROUTE, NOT_FOUND_ROUTE } from './routes' import { basicRoutes, EMPTY_ROUTE, NOT_FOUND_ROUTE } from './routes'
import { getToken, isNullOrWhitespace } from '@/utils' import { getToken, isNullOrWhitespace } from '@/utils'
import { useUserStore, usePermissionStore } from '@/store' import { useUserStore, usePermissionStore } from '@/store'
const isHash = import.meta.env.VITE_USE_HASH === 'true' const isHash = import.meta.env.VITE_USE_HASH === 'true'
export const router = createRouter({ export const router = createRouter({
history: isHash ? createWebHashHistory('/') : createWebHistory('/'), history: isHash ? createWebHashHistory('/') : createWebHistory('/'),
routes, routes: basicRoutes,
scrollBehavior: () => ({ left: 0, top: 0 }), scrollBehavior: () => ({ left: 0, top: 0 }),
}) })
export async function resetRouter() { export async function setupRouter(app) {
router.getRoutes().forEach((route) => {
const { name } = route
router.hasRoute(name) && router.removeRoute(name)
})
await addDynamicRoutes() await addDynamicRoutes()
setupRouterGuard(router)
app.use(router)
}
export async function resetRouter() {
const basicRouteNames = getRouteNames(basicRoutes)
router.getRoutes().forEach((route) => {
const name = route.name
if (!basicRouteNames.includes(name)) {
router.removeRoute(name)
}
})
} }
export async function addDynamicRoutes() { export async function addDynamicRoutes() {
@ -44,8 +52,14 @@ export async function addDynamicRoutes() {
} }
} }
export async function setupRouter(app) { export function getRouteNames(routes) {
await addDynamicRoutes() return routes.map((route) => getRouteName(route)).flat(1)
setupRouterGuard(router) }
app.use(router)
function getRouteName(route) {
const names = [route.name]
if (route.children && route.children.length) {
names.push(...route.children.map((item) => getRouteName(item)).flat(1))
}
return names
} }

View File

@ -53,5 +53,8 @@ export const usePermissionStore = defineStore('permission', {
this.accessRoutes = accessRoutes this.accessRoutes = accessRoutes
return accessRoutes return accessRoutes
}, },
resetPermission() {
this.$reset()
},
}, },
}) })

View File

@ -57,5 +57,9 @@ export const useTagsStore = defineStore('tag', {
router.push(filterTags[filterTags.length - 1].path) router.push(filterTags[filterTags.length - 1].path)
} }
}, },
resetTags() {
this.setTags([])
this.setActiveTag('')
},
}, },
}) })

View File

@ -1,4 +1,6 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useTagsStore, usePermissionStore } from '@/store'
import { removeToken, toLogin } from '@/utils' import { removeToken, toLogin } from '@/utils'
import api from '@/api' import api from '@/api'
@ -34,8 +36,13 @@ export const useUserStore = defineStore('user', {
} }
}, },
async logout() { async logout() {
const { resetTags } = useTagsStore()
const { resetPermission } = usePermissionStore()
removeToken() removeToken()
this.userInfo = {} resetTags()
resetPermission()
resetRouter()
this.$reset()
toLogin() toLogin()
}, },
setUserInfo(userInfo = {}) { setUserInfo(userInfo = {}) {

View File

@ -1,9 +1,11 @@
import { router } from '@/router' import { router } from '@/router'
export function toLogin() { export function toLogin() {
const currentRoute = unref(router.currentRoute)
const needRedirect = !currentRoute.meta.requireAuth && !['/404', '/login'].includes(router.currentRoute.value.path)
router.replace({ router.replace({
path: '/login', path: '/login',
query: { ...router.currentRoute.value.query, redirect: router.currentRoute.value.path }, query: needRedirect ? { ...router.currentRoute.value.query, redirect: router.currentRoute.value.path } : {},
}) })
} }

View File

@ -1,5 +1,5 @@
import { useUserStore } from '@/store' import { useUserStore } from '@/store'
import { isNullOrUndef, removeToken, toLogin } from '@/utils' import { isNullOrUndef } from '@/utils'
export function addBaseParams(params) { export function addBaseParams(params) {
if (!params.userId) { if (!params.userId) {
@ -7,21 +7,14 @@ export function addBaseParams(params) {
} }
} }
export function resolveResError(error = {}) { export function resolveResError(code, message) {
let { code, message } = error
if (isNullOrUndef(code)) {
// 未知错误
code = -1
message = message ?? '接口未知异常!'
} else {
switch (code) { switch (code) {
case 400: case 400:
message = message ?? '请求参数错误' message = message ?? '请求参数错误'
break break
case 401: case 401:
message = message ?? '登录已过期' message = message ?? '登录已过期'
removeToken() useUserStore().logout()
toLogin()
break break
case 403: case 403:
message = message ?? '没有权限' message = message ?? '没有权限'
@ -33,9 +26,8 @@ export function resolveResError(error = {}) {
message = message ?? '服务器异常' message = message ?? '服务器异常'
break break
default: default:
message = message ?? '操作异常!' message = message ?? `${code}】: 未知异常!`
break break
} }
} return message
return { code, message }
} }

View File

@ -1,4 +1,4 @@
import { getToken, toLogin } from '@/utils' import { getToken } from '@/utils'
import { resolveResError } from './helpers' import { resolveResError } from './helpers'
export function reqResolve(config) { export function reqResolve(config) {
@ -9,9 +9,7 @@ export function reqResolve(config) {
const token = getToken() const token = getToken()
if (!token) { if (!token) {
// * 未登录或者token过期的情况下,跳转登录页重新登录 return Promise.reject({ code: 401, message: '登录已过期,请重新登录!' })
toLogin()
return Promise.reject({ code: '-1', message: '未登录' })
} }
/** /**
@ -28,18 +26,33 @@ export function reqReject(error) {
} }
export function repResolve(response) { export function repResolve(response) {
const { noNeedTip } = response.config // TODO: 处理不同的 response.headers
const { data, status, config, statusText } = response
if (response.data?.code !== 0) { if (response.data?.code !== 0) {
const { code, message } = resolveResError(response?.data) const code = data?.code ?? status
!noNeedTip && $message.error(message)
/** 根据code处理对应的操作并返回处理后的message */
const message = resolveResError(code, data?.message ?? statusText)
/** 需要错误提醒 */
!config.noNeedTip && $message.error(message)
return Promise.reject({ code, message, error: response?.data }) return Promise.reject({ code, message, error: response?.data })
} }
return Promise.resolve(response?.data) return Promise.resolve(data)
} }
export function repReject(error) { export function repReject(error) {
const { noNeedTip } = error.response?.config || error.config if (!error || !error.response) {
const { code, message } = resolveResError(error.response?.data) const code = error?.code
!noNeedTip && $message.error(message) /** 根据code处理对应的操作并返回处理后的message */
const message = resolveResError(code, error.message)
$message?.error(message)
return Promise.reject({ code, message, error }) return Promise.reject({ code, message, error })
}
const { data, status, config } = error.response
const code = data?.code ?? status
const message = resolveResError(code, data?.message ?? error.message)
/** 需要错误提醒 */
!config?.noNeedTip && $message.error(message)
return Promise.reject({ code, message, error: error.response?.data })
} }