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

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

问题描述

如何访问通过 store 操作异步检索的 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
    }
  }
}

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

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 action 返回一个 promise 来实现,正如解释的那样 此处 并从 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 钩子中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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