Vue全局路由守卫 全局控制路由守卫权限 登录管理

登录页

触发登录事件

  methods: {
  //触发登录事件
    onSubmit() {
      // 如果登录成功
      if (this.id==='admin' && this.password==='123456') {
          this.$router.push('/main') //跳转页面
          localStorage.setItem('token','pass') //写入token
        }
        else{
         //如果登录失败
          localStorage.removeItem('token')
        }
    },
  },

注销

触发注销事件

  methods: {
    exit() {  
        localStorage.removeItem('token')
        this.$router.push('/login')
        console.log('退出登录')
    },
  },

全局路由守卫

写入router的index.js中

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next()
  }
  // 获取Token值
  const token = localStorage.getItem('token')
  if (!token) {
    // token 值不存在,强制跳转到登录页
    return next('/login')
  }
  // 存在token值,放行
  next()
})
posted @ 2022-03-21 22:34  朝颜浅语  阅读(229)  评论(0编辑  收藏  举报