网站中很常见的一个需求是登录验证,即未登录时跳转至登录页。在vue项目中,使用vue-route 提供的 beforeRouteUpdate函数可以实现路由判断。

首先在配置的路由中加入 requireAuth: true,代表进入该路由需要验证

  1. 1. {
  2. 2. path:'/XXXXX',
  3. 3. name:'xxxx',
  4. 4. meta: {
  5. 5. requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
  6. 6. },
  7. 7. component: resolve => require(['..xxxxx.vue'], resolve)
  8. 8. }

然后使用 router.beforeEach 在main.js中注册一个全局的函数。

这里使用localStorage作为判断,localStorage的生命周期是永久的,真实项目中不建议使用。大家可以使用Vuex作为数据存储。

  1. 1. router.beforeEach((to, from, next) => {
  2. 2. if (to.matched.some(record => record.meta.requireAuth)){ // 判断该路由是否需要登录权限
  3. 3. if (localStorage.user_id) { // 判断当前的user_id是否存在 ; 登录存入的user_id
  4. 4. next();
  5. 5. }
  6. 6. else {
  7. 7. next({
  8. 8. path: '/login',
  9. 9. query: {redirect: to.fullPath} // 将要跳转路由的path作为参数,传递到登录页面
  10. 10. })
  11. 11. }
  12. 12. }
  13. 13. else {
  14. 14. next();
  15. 15. }
  16. 16. })

注意:router.beforeEach方法要创建在new Vue之前。

  • router.beforeEach 的三个参数
  1. to:Route:即将要进入的路由
  2. from:Route:当前正要离开的路由
  3. next:function()
  • next的用法
  1. next() :进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
  2. next(false) :中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  3. next( { path:’/login’ } ): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

    确保要调用 next 方法,否则钩子就不会被 resolved。


    最后,在执行登录操作时,可以使用跳转时传递的参数回到进入登录前的路由 ```
  4. submitForm(){
  5. var self = this;
  6. //这里写登录的操作
  7. //登录成功时
  8. localStorage.user_id=1;
  9. if(self.$route.query.redirect){ //如果存在参数
  10. let redirect = self.$route.query.redirect;
  11. self.$router.push(redirect);//则跳转至进入登录页前的路由
  12. }else{
  13. self.$router.push(‘/index’);//否则跳转至首页
  14. }
  15. }, ``` 这样,整个登录的流程就搞定了。