简体   繁体   English

Vue Router + Vuex:如何让 beforeEach 路由守卫等待 Vuex 状态改变?

[英]Vue Router + Vuex: how to make beforeEach route guard wait for Vuex state change?

In my SPA, part of the initialization when the page loads is fetching the logged in user from the API, and then the user record is stored in the state alongside with initialized flag.在我的 SPA 中,页面加载时的部分初始化是从 API 获取登录用户,然后将用户记录与已initialized标志一起存储在状态中。

In the router beforeEach guard I need to check whether the user is logged in, but for it to function correctly, I need to wait until the initialized flag is set to true .在路由器中, beforeEach守卫之前我需要检查用户是否已登录,但要使其正常运行,我需要等到initialized标志设置为true How can I make my function wait for that?我怎样才能让我的函数等待它? Should I hook into the store and create a watcher, or set up another variable as a promise or something?我应该挂入商店并创建一个观察者,还是设置另一个变量作为承诺或其他东西?

Thanks!谢谢!

You can implement a rudimentary "pause" feature on the router like this (code is untested):您可以像这样在路由器上实现基本的“暂停”功能(代码未经测试):

// Router is initially not paused
let pausedResolve = null
let pausedPromise = Promise.resolve()

router.beforeEach(async (to, from, next) => {
  await pausedPromise
  next()
})

function pause() {
  if (!pausedResolve) {
    pausedPromise = new Promise(resolve => pausedResolve = resolve)
  }
}

function resume() {
  if (pausedResolve) {
    pausedResolve()
    pausedResolve = null
  }
}

After creating the router, immediately call pause() , then after logging in call resume() (you can do this in your Vuex code maybe).创建路由器后,立即调用pause() ,然后在登录后调用resume() (您可以在 Vuex 代码中执行此操作)。

The benefit of this implementation is that the router code is not dependent on the Vuex code (it's generally a good idea to keep code loosely-coupled whenever possible).这种实现的好处是路由器代码不依赖于 Vuex 代码(尽可能保持代码松散耦合通常是个好主意)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM