加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vue登录注册及token验证实现代码

发布时间:2020-12-17 02:40:36 所属栏目:百科 来源:网络整理
导读:在大多数网站中,实现登录注册都是结合本地存储cookie、localStorage和请求时验证token等技术。而对于某些功能页面,会尝试获取本地存储中的token进行判断,存在则可进入,否则跳到登录页或弹出登录框。 而在vue单页中,我们可以通过监控route对象,从中匹配

在大多数网站中,实现登录注册都是结合本地存储cookie、localStorage和请求时验证token等技术。而对于某些功能页面,会尝试获取本地存储中的token进行判断,存在则可进入,否则跳到登录页或弹出登录框。

而在vue单页中,我们可以通过监控route对象,从中匹配信息去决定是否验证token,然后定义后续行为。

具体实现代码如下:

1. 利用router.beforeEach钩子,判断目标路由是否携带了相关meta信息

{ let token = window.localStorage.getItem('token') if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === null)) { next({ path: '/login',query: { redirect: to.fullPath } }) } else { next() } }) export default router

2. watch route对象。原理同上。

// App.vue export default { watch:{ '$route':function(to,from){ let token = window.localStorage.getItem('token');          if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === null)) {            next({            path: '/login',           query: { redirect: to.fullPath }            })          } else {        next()          }    }   } }

总结

以上所述是小编给大家介绍的vue登录注册及token验证实现代码。编程之家 52php.cn 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读