如何访问 vue-router 中的异步存储数据以便在 beforeEnter 挂钩中使用?

新手上路,请多包涵

如何访问通过存储操作异步检索的 beforeEnter 中的存储数据?

 import store from './vuex/store';

store.dispatch('initApp'); // in here, async data will be fetched and assigned to the store's state

// following is an excerpt of the routes object:
{
  path: '/example',
  component: Example,
  beforeEnter: (to, from, next) =>
  {
    if (store.state.asyncData) {
      // the above state is not available here, since it
      // it is resolved asynchronously in the store action
    }
  }
}

这在第一个页面加载或页面重新加载后尤其重要,此时正在获取初始数据并且路由器需要等待该数据以允许用户访问该页面或不允许。

路由器是否可以“等待”获取数据?或者结合异步 vuex 存储数据处理导航守卫的最佳方式是什么?

(哦,预填充“asyncData”不是解决方案,因为 beforeEnter 挂钩需要根据数据库中的真实数据而不是默认数据做出决定)

原文由 santacruz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 789
1 个回答

您可以通过从 vuex 操作返回一个承诺来做到这一点,正如 此处 所解释的那样,并从 beforeEnter 本身内部调用调度。

代码应如下所示:

 import store from './vuex/store';

// following is an excerpt of the routes object:
{
  path: '/example',
  component: Example,
  beforeEnter: (to, from, next) =>
  {
    store.dispatch('initApp').then(response => {
        // the above state is not available here, since it
        // it is resolved asynchronously in the store action
    }, error => {
        // handle error here
    })
  }
}

原文由 Saurabh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题