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

标签 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

最佳答案

如果您已经定向到 '/login',则必须阻止调用 next('/login')

例如:

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

关于vue.js - Vue-router beforeEach 在使用 next() 时陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45976708/

相关文章:

javascript - Vue js如何在整个项目中隐藏url中的查询字符串

javascript - 如何在Vue-router中使用$router.push?

vue.js - 如何检查vue-router中是否存在命名 View

javascript - i18next 单一翻译字符串回退/默认(Vue JS)

html - 为什么我的 Google map 会溢出我的 CSS 网格容器?

javascript - Vuetify 自动完成组件 : set value

typescript - Vue + Typescript vue-router 和参数类型

javascript - Vue/Webpack/Typescript - 如何使用 jQuery 插件

vue.js - 代码拆分的动态导入导致 : ESLint Parsing Error 'import'

javascript - Vue 在函数中使用 Plugin