首页 > 解决方案 > 异步/等待 Vuex

问题描述

我想在创建的钩子中调用一个动作,等到完成并在同一个钩子中显示结果。那可能吗?

我试图将 async / await 放在操作中,但没有帮助。
这是action具有 async 功能的属性store

 actions: {
    async FETCH_USER({commit}) {
      await firebase.firestore().collection('test').get().then(res => {
        commit('FETCH_USER', res.docs[0].data())
      })
    }
  }
   created() {
     this.FETCH_USER()
     console.log(this.GET_USER)
   },
   methods: {
     ...mapActions([
       'FETCH_USER'
     ]),
     login() {
       if(this.$refs.form.validate()) {
         console.log('welcome')
       }
     }
   },
   computed: {
     ...mapGetters([
       'GET_USER'
     ])
   }
export default new Vuex.Store({
  state: {
    user: null
  },
  getters: {
    GET_USER: state => state.user
  },
  mutations: {
    FETCH_USER(state, user) {
      state.user = user
    }
  },
  actions: {
    FETCH_USER({commit}) {
      firebase.firestore().collection('test').get().then(res => {
        commit('FETCH_USER', res.docs[0].data())
      })
    }
  }
})

标签: asynchronousvue.jsasync-awaitvuex

解决方案


async/await版本

async FETCH_USER({ commit }) {
  const res = await firebase.firestore().collection('test').get()
  const user = res.docs[0].data()
  commit('FETCH_USER', user)
  return user
}
async created() {
  // The action returns the user out of convenience
  const user = await this.FETCH_USER()
  console.log(user)

  // -- or --

  // Access the user through the getter
  await this.FETCH_USER()
  console.log(this.GET_USER)
}

您需要等待操作调用,因为它是一个异步函数。

承诺版

FETCH_USER({ commit }) {
  return firebase.firestore().collection('test').get().then(res => {
    const user = res.docs[0].data()
    commit('FETCH_USER', user)
    return user
  })
}
created() {
  this.FETCH_USER().then(user => {
    console.log(user)
  })

  // -- or --

  this.FETCH_USER().then(() => {
    console.log(this.GET_USER)
  })
}

推荐阅读