使用vue如何实现登录注册及token验证

亚连
亚连 原创
2018-06-20 17:04:48 5062浏览

在vue单页中,我们可以通过监控route对象,从中匹配信息去决定是否验证token,然后定义后续行为。下面通过实例代码给大家分享vue登录注册及token验证功能,需要的朋友参考下吧

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

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

具体实现代码如下:

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

// router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
 {
  path: '/',
  component: require('./views/Home'),
  meta: {
   requiresAuth: true
  }
 },
]
const router = new VueRouter({
 routes: routes
})
router.beforeEach((to, from, next) => {
 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对象。原理同上。

<script>
  // 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()
          }
      }
    }
  }
</script>

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在JS中如何实现预览效果

使用three.js制作一个项目

在Node中如何使用ES6语法(详细教程)

详细介绍js中this对象用法

以上就是使用vue如何实现登录注册及token验证的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。