文章目录
- 前言
- 一、后端代码
- 二、前端代码
- 1.接口调用
- 2.界面代码
- 3.事件代码
- 三、效果
- 总结
前言
这里来演示用户登出。
一、后端代码
/**
* 登出
* @param token token
* @return Result
*/
@RequestMapping("logout")
public Result logout(@RequestHeader("Authorization") String token){
Map<String, Object> claims =ThreadLocalUtil.get();
String Username = (String) claims.get("username");
User user = userSerivce.findUserByName(Username);
String message="用户名/密码不正确";
if(user!=null){//用户存在
if(token!=null&&token.contains("Bearer")){
String tokenStr = token.substring(token.indexOf("Bearer") + 7);
boolean verify = JwtUtils.verify(tokenStr);
if(verify&&tokenStr.equals(loginStorage.get(user.getId().toString()))){
loginStorage.remove(user.getId().toString());
return Result.success("登出成功");
}
}
}
return Result.error(message);
}
二、前端代码
1.接口调用
export const userLogoutService = ()=>{
return request.get('/user/logout')
}
2.界面代码
<el-dropdown placement="bottom-end" @command="handleCommand">
<span class="el-dropdown__box">
<el-avatar
:src="useUserInfoStore().getUserInfo().userPic ? 'avatar/' + useUserInfoStore().getUserInfo().userPic : avatar" />
<el-icon>
<CaretBottom />
</el-icon>
</span>
<template #dropdown>
<el-dropdown-menu>
<div v-if="useUserInfoStore().getUserInfo().nickname" style=" text-align: center; "><span
class="accent" data-v-6b0c93fd=""><strong>你好,{{
useUserInfoStore().getUserInfo().nickname }}</strong></span></div>
<el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
<el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
<el-dropdown-item command="resetpassword" :icon="EditPen">重置密码</el-dropdown-item>
<el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
3.事件代码
import { ElMessage, ElMessageBox } from 'element-plus'
import { userInfoService, userLogoutService } from '@/api/user.js'
import { useTokenStore } from '@/stores/token.js'
import useUserInfoStore from '@/stores/userInfo.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const logout = async () => {
//1.调用后台登出接口
let result = await userLogoutService()
if (result.code == 0) {
//2.清空tokenStore和userInfoStore
useTokenStore().removeToken()
useUserInfoStore().removeUserInfo()
//3.跳转到login登录界面
router.push("/login")//组合式
ElMessage({
type: 'info',
message: '退出成功',
})
}
}
const handleCommand = (command) => {
if (command === 'logout') {
//退出登录
ElMessageBox.confirm(
'您确认退出登录吗?',
'温馨提示',
{
confirmButtonText: '确认',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(() => {
logout()
})
.catch(() => {
//用户点击了取消
ElMessage({
type: 'info',
message: '取消退出',
})
})
}else{
router.push("/user/"+command)//组合式
}
}
三、效果
总结
回到顶部