代码之家  ›  专栏  ›  技术社区  ›  Kyll GUISSOUMA Issam

如何在加载某些异步数据(在Vuex存储中)之前阻止任何路由?

  •  1
  • Kyll GUISSOUMA Issam  · 技术社区  · 7 年前

    在我的应用程序中,在路由开始之前(例如用户会话),我需要在Vuex存储中加载一些数据。

    竞赛条件的示例如下:

    // In routes definition
    {
      name: 'login',
      path: '/login',
      component: Login,
      meta: {
        goToIndexIf: () => store.getters['auth/loggedIn']
      }
    }
    

    在这种情况下,路由保护可能在从服务器接收到用户之前执行。

    使用条件呈现没有帮助,因为使用或不使用 <router-view v-if="storeReady"> 在呈现的模板中。

    如何使所有路由等待一些异步数据?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Kyll GUISSOUMA Issam    7 年前

    解决方案很简单。增加一个 init 或同等Vuex action 去你商店的相关部分。
    它应该返回 Promise 在您的应用程序 绝对需要 * :

    init ({ dispatch }) {       // Could also be async and use await instead of return
      return Promise.all([
        dispatch('getUserSession'), // Using another action
        dispatch('auth/init'),      // In another module
        fetch('tehKittenz')         // With the native fetch API
        // ...
      ])
    }
    

    上面的代码可以使用返回 许诺 .

    然后创建一个 global navigation guard 在路由器中使用 beforeEach .
    这个守卫将等待 dispatch 去商店。

    // In your router initialization code
    const storeInit = store.dispatch('init')
    
    // Before all other beforeEach
    router.beforeEach((to, from, next) => {
      storeInit.then(next)
        .catch(e => {
          // Handle error
        })
    })
    

    这样,如果路由发生在存储完全加载之前,那么路由器只需等待。
    如果路由发生在之后,则承诺将已经位于 fulfilled 状态和路由将继续。

    别忘了用 conditional rendering 以便在路由等待数据时不显示空白屏幕。


    * :这将阻止所有路由和导航,只要正在获取数据。小心。