如何在vue-router中访问异步存储数据以便在beforeEnter hook中使用? [英] How to access async store data in vue-router for usage in beforeEnter hook?

查看:256
本文介绍了如何在vue-router中访问异步存储数据以便在beforeEnter hook中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过商店操作以异步方式检索的beforeEnter中访问商店数据?

How is it possible to access store data in beforeEnter which is retrieved asynchronously via the store action?

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
    }
  }
}

这在第一页尤为重要加载或页面重新加载后,当获取init数据并且路由器需要等待该数据允许用户访问该页面时。

This is especially important on the first page load or after a page reload, when the init data is being fetched and the router needs to wait for that data to either allow the user to access that page or not.

路由器是否可以等待获取数据?
或者与异步vuex商店数据结合处理导航防护的最佳方法是什么?

Is it possible for the router to "wait" for the data to be fetched? Or what's the best way to handle navigation guard in combination with async vuex store data?

(哦,预先填充asyncData不能是解决方案,因为beforeEnter钩子需要从数据库中确定真实数据,而不是默认数据。

(oh and pre-populating "asyncData" can't be the solution, since the beforeEnter hook needs to make its decision on real data from the database, not default data)

推荐答案

你可以做它通过从vuex操作返回一个承诺,因为这里解释并从 beforeEnter 本身。

You can do it by returning a promise from vuex action, as it is explained here and call the dispatch from within the beforeEnter itself.

代码应如下所示:

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
    })         
  }
}

这篇关于如何在vue-router中访问异步存储数据以便在beforeEnter hook中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆