编写logout函数,通过封装好的get向退出地址发送请求,成功后删除当前的token,并返回登陆页面:
function logout(success,failure=defaultFailure){
get("/api/auth/logout",()=>{
deleteAccessToken()
ElMessage.success("退出登录成功,欢迎您再次使用")
success()
},failure)
}
记得将logout get post导出,暴露给组件。
在index.vue中编写退出按钮与对应的方法:
<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>
退出后转至登录页面。
在router中添加index导航页面的路由:
path:'/index',
name:'index',
component:()=>import('@/views/welcome/IndexView.vue'),
}
退出登录后token被删除
此时输入index可以直接访问登陆后界面,需要配置路由守护:
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()
}
})
``