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

竞赛条件的一个例子如下:

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

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

使用条件渲染没有帮助,因为在渲染模板中执行路由保护时,无论是否使用<router-view v-if="storeReady">.

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

推荐答案

解决办法很简单.将init或等效Vuex action添加到store 的相关部分

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
    // ...
  ])
}

上面的代码可以使用任何返回Promise的代码.

然后用beforeEach在路由上创建一个global navigation guard

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

这样,如果在存储完全加载之前进行路由,路由只需等待

不要忘记使用conditional rendering之类的东西,以免在路由等待数据时显示空白屏幕.


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

Vue.js相关问答推荐

为什么在Vue.js中修改非react 性似乎是react 性的?

Vue.js编译的render函数不起作用

在 VueJS 中,将变量而不是组件的字符串名称传递给动态组件的 :is 属性不起作用

vue3 + pinia:如何从?store 中获取一个值

当用户在嵌套路由中时激活链接

nuxt.js auth 始终重定向到登录,而不是允许转到带有 auth: false 的页面,

vuex 未知动作类型:addTodo

路径别名在 vue 脚本块中不起作用

Vuex 和 Event Bus 有什么区别?

如何使用 v-on:change 将输入文本传递给我的 vue 方法?

Vuetify v-data-table ,如何在 HTML 中呈现标题文本?

Vue watch 意外调用了两次

vue js 组件中的 this.$route 只返回 undefined

在按键 vuejs 中只允许数字和一个小数点后 2 位限制

为什么 vue 中的 @mouseover 操作不起作用

如何从 vue.js 中的自定义组件中冒泡点击事件?

Nuxt:显示静态文件夹中的本map像

如何在 NPM 上创建和发布 Vuejs 组件

Vue:如何在按钮单击时调用 .focus()

laravel vuejs/axios put request Formdata 为空