javascript - Vue Router next 回调总是在 beforeEach 中调用

标签 javascript vue.js vue-router

我正在为一些网址创建一个守卫。我使用 beforeEach 来评估元参数并决定用户是否可以看到页面。

router.beforeEach((to, from, next) => {
  var isLoggedIn = localStorage.getItem('cacheTokenId');

  if(to.meta.guestOnly && isLoggedIn) {
    next({ name: 'cars' })
  } else if(to.meta.authOnly && !isLoggedIn) {
    console.log("authOnly")
    next({ name: 'login' })
  }

  next()
})

我的问题是最后一个下一个(外部条件)总是被执行。我认为 next() 在调用它的地方停止了执行。

目前,我的解决方案已将最后一个 next() 移至 else 条件内:

if(to.meta.guestOnly && isLoggedIn) {
    console.log("guestOnly")
    next({ name: 'cars' })
  } else if(to.meta.authOnly && !isLoggedIn) {
    console.log("authOnly")
    next({ name: 'login' })
  } else {
    next()
  }

为什么需要这个,我错过了什么吗?

最佳答案

I thought next() stopped the execution at the point where it was called.

next() 只是一个函数调用,它不会执行语言规范之外的操作。它不会抛出异常,因此不会停止流程。

all examples I have found does not have [a return statement after next()]

这是因为您发现的每个示例都避免在导航保护处理程序中使用我们在 JavaScript 中找到的常用逻辑多次调用 next() ,例如显式 else 就像你正在使用的那样。

关于javascript - Vue Router next 回调总是在 beforeEach 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51881872/

相关文章:

javascript - jQuery 将文本字段的值从不同的表单复制到另一个表单的文本字段

javascript - jQuery:未捕获类型错误:对象#<Object>没有方法 'apply'

json - 如何使用 Vue $set 更改嵌套 JSON 的值?

vue.js - [Vue 警告] : Unknown custom element: <router-view> - did you register the component correctly?

vue.js - Vue JS 路由器查询传递并绑定(bind)到 axios

c# - 使用 ASP.NET MVC 数据绑定(bind) View 模型显示 JQuery 对话框的最佳方式

javascript - 比较两个对象看是否相等

javascript - Vue JS - 有条件地在一个组件中显示信息

vue.js - Vuejs - 如何在点击时进行 v-for 循环

javascript - 努力将数据传输到子组件