未定义 beforeEach localStorage 中的 Vue 2 路由器

Vue 2 router in beforeEach localStorage is not defined

需要做一些类似中间件的事情,需要检查用户是否有令牌,然后允许转换

router.beforeEach((to, from, next) => {
    const accessNeed = ['Dashboard',]
    if (localStorage.getItem("token")){
        if (!accessNeed.includes(to.name)) {
            next({ name: 'Home' })
        }else{
            next()
        }
    }else{
        next()
    }
})

您正在使用 Nuxt,或者只是 Vue SSR 包。所以你必须确保,代码只在客户端执行:

router.beforeEach((to, from, next) => {
  if (!process.client) {
    next()
    return
  }
    
  const accessNeed = ['Dashboard']

  if (window && window.localStorage.getItem("token")){
    if (!accessNeed.includes(to.name)) {
      next({ name: 'Home' })
    } else{
      next()
    }
  }

  next()
})