4-05:退出登录方案实现

284 阅读1分钟

4-05:退出登录方案实现

退出登录 一直是一个通用的前端实现方案,对于退出登录而言,它的触发时机一般有两种:

  1. 用户主动退出
  2. 用户被动退出

其中:

  1. 主动退出指:用户点击登录按钮之后退出
  2. 被动退出指:token 过期或被 其他人”顶下来“ 时退出

那么无论是什么退出方式,在用户退出时,所需要执行的操作都是固定的:

  1. 清理掉当前用户缓存数据
  2. 清理掉权限相关配置
  3. 返回到登录页

那么明确好了对应的方案之后,接下来咱们就先来实现 用户主动退出的对应策略

store/modules/user.js 中,添加对应 action

import router from '@/router'

logout() {
    this.commit('user/setToken', '')
    this.commit('user/setUserInfo', {})
    removeAllItem()
    router.push('/login')
}

为退出登录按钮添加点击事件,触发 logoutaction

import { useStore } from 'vuex'

const store = useStore()
const logout = () => {
  store.dispatch('user/logout')
}

那么至此,我们就完成了 用户主动退出 对应的实现。