Vue-router beforeEach在使用next()时陷入无限循环

时间:2017-08-31 08:24:44

标签: vue.js vue-router

我遇到了这个问题,我无法使用next('/login')。这是我的代码:

*/ all imports that are needed 

Vue.use(Router);

const routes = [
{path: '/', component: Home},
{path: '/admin', component: Admin},
{path: '/login', component: Login}]

var route = new Router({
routes: routes,
mode: 'history' });

route.beforeEach((to, from , next) => {
console.log(to.fullPath)
next('/login');
});

new Vue({
  el: '#app',
  router: route,
  template: '<App/>',
  components: {
    App
  }
})

当我只使用next()时它起作用但是当我给next()函数一个路径时它会陷入无限循环

console screenshot

1 个答案:

答案 0 :(得分:10)

如果您已经指示next('/login'),则必须阻止致电'/login'

例如:

route.beforeEach((to, from , next) => {
  console.log(to.fullPath)
  if (to.path !== '/login') {
    next('/login');
  } else {
    next();
  }
});