0

我遇到了一个我认为不应该发生的循环问题。在 Nuxt 嵌套动态页面组件(_id.vue)中,我想检查导航防护to.hash中是否不为空,beforeRouteLeave但是当我执行此检查并且它是真的时,我得到RangeError: Maximum call stack size exceeded.

我做了一个测试,console.log('test')我看到它被称为不间断,直到浏览器停止它以防止它崩溃。

  beforeRouteLeave (to, from, next) {
    // there is hash and if the user click the back button of the browser, I want to return him to the position of the product file where he was before the click to enter into it
    if (to.name.startsWith('index___') && to.hash !== '') {
      next({ path: to.path, hash: `#${this.$route.params.id}` })
    } else {
      next()
    }
  }

仅当我测试to.hash !== ''但不测试to.hash === '#ct'并且我不明白为什么时才会发生这种情况?

如果用户来自路径中带有哈希的索引页面,如果他单击浏览器的后退按钮,我想将他带回到他单击浏览页面时所在的_id页面位置。

有人可以帮助我了解这里发生了什么吗?

谢谢

4

1 回答 1

2

我在Vue 论坛上得到了一个对我有帮助的答案,我不知道那next()是在回忆这个过程,我的beforeRouteLeave钩子正在重新评估to.hash我设置的导致循环的新值(to.hash !== ''总是正确的)。

确保在第一次设置后测试将通过条件的相反值。

这是解决问题的代码:

  beforeRouteLeave (to, from, next) {
    if (to.name.startsWith('index___') && (to.hash === '#ct' | (to.hash !== `#${this.$route.params.id}` && to.hash !== ''))) {
      next({ path: to.path, hash: `#${this.$route.params.id}` })
    } else {
      next()
    }
  }

我希望它可以帮助别人。

于 2020-09-24T01:15:13.340 回答