笑着迷惘 發表於 2020-9-22 15:26:00

vue 路由守卫,未登录强制跳转到登录页

<p>main.js 中,</p>
<div class="cnblogs_Highlighter">
<pre class="brush:javascript;gutter:true;">//挂载路由导航守卫
router.beforeEach((to, from, next) =&gt; {<br>  <span style="color: rgba(192, 192, 192, 1)"> //获取token</span>
    const hasToken = getToken();
    <span style="color: rgba(192, 192, 192, 1)">// to 将要访问的路径
    // from 代表从哪个路径跳转而来
    // next 是一个函数,表示放行
    // next() 放行   next('/login') 强制跳转
    // 如果用户访问的登录页,直接放行</span>
    if (hasToken) {
      if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
      }
      next()
    } else {
      <span style="color: rgba(192, 192, 192, 1)">// 没有token,强制跳转到登录页</span>
      if (whiteList.indexOf(to.path) !== -1) {
            next()
      } else {
            next(`/login`)
            // next(`/login?redirect=${to.path}`)
            NProgress.done()
      }
    }
})
</pre>
</div>
<p>  </p><br><br>
来源:https://www.cnblogs.com/moguzi12345/p/13712461.html
頁: [1]
查看完整版本: vue 路由守卫,未登录强制跳转到登录页