How to access async store data in vue-router for usage in beforeEnter hook?

后端 未结 3 1622
自闭症患者
自闭症患者 2020-12-08 07:02

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

import store from \'./vuex/store\';

store.dis         


        
3条回答
  •  庸人自扰
    2020-12-08 07:51

    I've solved this issue by using store.watch() for no initial value and return the latest value when already initialized.

    Here is my sample code

    async function redirectIfNotAuth (to, from, next) {
      const user = await getUserState()
      if (user === null) {
        next({ name: 'auth' })
      } else {
        next()
      }
    }
    
    function getUserState () {
      return new Promise((resolve, reject) => {
        if (store.state.user === undefined) {
          const unwatch = store.watch(
            () => store.state.user,
            (value) => {
              unwatch()
              resolve(value)
            }
          )
        } else {
          resolve(store.state.user)
        }
      })
    }
    
    
    /* STORE */
    const store = new Vuex.Store({
      state: {
        user: undefined
      }
    })
    
    /* ROUTER */
    new Router({
      routes: [
        {
          path: '',
          name: 'home',
          component: Home,
          beforeEnter: redirectIfNotAuth
        },
        {
          path: '/signin',
          name: 'auth',
          component: Auth,
        }
      ]
    })
    

提交回复
热议问题