退出登录以及路由守卫实现

This commit is contained in:
Amadeus 2024-05-06 22:43:50 +08:00
parent 8e31cc3696
commit 840170b66e
4 changed files with 89 additions and 4 deletions

View File

@ -13,7 +13,7 @@ const defaultError = (err) => {
ElMessage.warning('发生了一些错误,请联系管理员') ElMessage.warning('发生了一些错误,请联系管理员')
} }
function takeAccess() { function takeAccessToken() {
const str = localStorage.getItem(authItemName) || sessionStorage.getItem(authItemName) const str = localStorage.getItem(authItemName) || sessionStorage.getItem(authItemName)
if (!str) return null; if (!str) return null;
const authObj = JSON.parse(str) const authObj = JSON.parse(str)
@ -39,6 +39,20 @@ function deleteAccessToken(){
sessionStorage.removeItem(authItemName) sessionStorage.removeItem(authItemName)
} }
/*
获取请求头
*/
function accessHeader() {
const token = takeAccessToken();
return token ? {
'Authorization' : `Bearer ${takeAccessToken()}`
} : {
}
}
function internalPost(url , data , header , success ,failure , error = defaultError) { function internalPost(url , data , header , success ,failure , error = defaultError) {
axios.post(url,data, {headers: header}).then(({data}) => { axios.post(url,data, {headers: header}).then(({data}) => {
if (data.code ===200){ if (data.code ===200){
@ -59,6 +73,17 @@ function internalGet(url , header , success ,failure , error = defaultError) {
}) .catch(err => error(err)) }) .catch(err => error(err))
} }
/*
封装get方法和post方法
*/
function get(url , success , failure = defaultFailure) {
internalGet(url , accessHeader() ,success , failure)
}
function post(url , data , success , failure = defaultFailure){
internalPost(url , data , accessHeader() ,success ,failure)
}
function login(username , password , remember , success , failure = defaultFailure) { function login(username , password , remember , success , failure = defaultFailure) {
internalPost('api/auth/login', { internalPost('api/auth/login', {
username: username , username: username ,
@ -72,4 +97,19 @@ function login(username , password , remember , success , failure = defaultFailu
}, failure) }, failure)
} }
export {login}
/*
退出函数
*/
function logout(success ,failure = defaultFailure){
get('/api/auth/logout' , () => {
deleteAccessToken()
ElMessage.success('退出登录成功,欢迎您再次使用')
success()
} , failure)
}
function unauthorized(){
return !takeAccessToken()
}
export {login , logout , get ,post , unauthorized}

View File

@ -1,4 +1,5 @@
import {createRouter , createWebHistory} from "vue-router"; import {createRouter , createWebHistory} from "vue-router";
import {unauthorized} from "@/net";
const router = createRouter( { const router = createRouter( {
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@ -9,14 +10,32 @@ const router = createRouter( {
component:() => import('@/views/WelcomeView.vue'), component:() => import('@/views/WelcomeView.vue'),
children: [ children: [
{ {
//什么都不配置的情况
path: '', path: '',
name: 'welcome-login', name: 'welcome-login',
component: () => import('@/views/welcome/LoginPage.vue') component: () => import('@/views/welcome/LoginPage.vue')
} }
] ]
}, {
/*
添加路由
*/
path: '/index',
name: 'index',
component: () => import('@/views/IndexView.vue')
} }
] ]
}) })
router.beforeEach((to, from , next) =>{
const isUnauthorized = unauthorized()
if (to.name.startsWith('welcome-') && !isUnauthorized){
next('index')
}else if (to.fullPath.startsWith('/index') && isUnauthorized) {
next('/')
}else {
next()
}
})
export default router export default router

View File

@ -0,0 +1,19 @@
<script setup>
import {logout} from "@/net";
import router from "@/router";
function userLogout(){
logout(()=> router.push('/'))
}
</script>
<template>
<div>
<el-button @click="userLogout">退出登录</el-button>
</div>
</template>
<style scoped>
</style>

View File

@ -2,6 +2,10 @@
import { User , Lock} from '@element-plus/icons-vue' import { User , Lock} from '@element-plus/icons-vue'
import {reactive, ref} from "vue"; import {reactive, ref} from "vue";
import {login} from "@/net"; import {login} from "@/net";
/*
导入路由
*/
import router from "@/router";
const formRef = ref() const formRef = ref()
@ -24,7 +28,10 @@ function userLogin(){
formRef.value.validate((valid) => { formRef.value.validate((valid) => {
if (valid){ if (valid){
login(form.username , form.password ,form.remember , ()=>{ login(form.username , form.password ,form.remember , ()=>{
/*
路由到index
*/
router.push('/index')
}) })
} }
}) })