简单得设置全局路由守卫,用通俗的话去注释
在router里面设置全局路由守卫(一般在全局的路由里面设置一道门)

 {
      path: '/about',
      name: 'about',
      // 添加标识守卫,如果有auth说明有门卫
      meta: {
        auth: true
      },
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    }

通过设置全局的前置守卫beforeEach

// 创建钩子函数
router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    // 如果有门卫就判断有没有钥匙
    const token = localStorage.getItem('token')
    if (!token) {
      // 如果没有钥匙就跳转到登录页面,为了用户体验 记录一下当前地址
      next({
        path: '/login',
        query: {
          loginto: to.path
        }
      })
    } else {
      // 如果没有钥匙就跳转到登录页面
      next('/login')
    }
  } else {
    // 如果没有门卫就直接进去
    next()
  }
})
Last modification:September 23, 2019
If you think my article is useful to you, please feel free to appreciate