【问题标题】:Vuejs router forEach not firedVuejs路由器forEach没有被解雇
【发布时间】:2017-12-21 12:18:27
【问题描述】:

我用vue-router 配置了VueJs,一切正常。除了,我想在路由器的beforEach 事件上添加一个处理程序。

我已经尝试了很多并按照文档进行操作,但仍然无法正常工作。我的代码是:

代码:

const router = new VueRouter({
    routes: routes,

});

router.beforeEach = function(to, from, next){
    console.log(to);
    if (to.path !== '/' && data.Registration.loggedIn === false) {
        console.log('not logged in');
        this.push('/');
    }
    console.log('logged in');

};

const flowApp = new Vue({
    el: '#vue_registration_app',
    router, data, methods
});

即使console.log(to) 也无济于事。

【问题讨论】:

  • 您在浏览页面吗?这应该工作
  • 是的,我导航到其他页面
  • 好吧,你可以检查一下这个小提琴jsfiddle.net/samayo/xzjabL5p它就像你在做的那样工作
  • 实际检查一下,jsfiddle.net/samayo/xzjabL5p/1 我添加了您的示例中缺少的 next() 方法
  • 太棒了!现在至少发生了一些事情。

标签: javascript vuejs2 vue-router


【解决方案1】:

在文档中建议这样使用它:

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

相反,您正在这样做:

const router = new VueRouter({ ... })

router.beforeEach = (to, from, next) => {
  // ...
})

因此,不要重新分配 beforeEach,而是使用您的函数作为参数调用 beforeEach 函数,一切都应该正常

【讨论】:

    【解决方案2】:

    来自Vue-router documentation "确保始终调用next 函数,否则永远无法解决挂钩。" – 我认为它应该有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2016-07-15
      相关资源
      最近更新 更多