【问题标题】:Vuex — handling network busy status globally?Vuex——全球处理网络繁忙状态?
【发布时间】:2020-12-08 04:05:26
【问题描述】:

我有一个 Vue/Vuex 应用程序,我使用布尔值 networkBusyStatus 来存储 API 调用完成的时间。

当应用程序加载时,我会触发很多不同的调用,因此当我在我的一个组件中观看 networkBusyStatus 并控制 newVal 时,它可以预见地交替出现真、假、真、假。

全局观看以了解“假”何时真正最终“假”的正确方法是什么。即加载已正式且完全完成?

【问题讨论】:

  • 使用一个在加载开始时增加并在加载结束时减少的计数器,而不是布尔值。或者您推送到的字符串列表,以便您知道仍在加载的内容。

标签: vue.js vuex


【解决方案1】:

您可以使用Promise.all 方法来确保networkBusyStatus 状态仅在所有API 调用都已解决时才会发生变化。

.vue 文件

export default {
  mounted() { // as you know, the created hook can also be used here
    this.$store.commit('loading', true)
    Promise.all([this.$store.dispatch('fetchAsyncData'), this.$store.dispatch('fetchAnotherAsyncDataOnTheSameComponent')]).then(values => {
     this.$store.commit('loading', false) // commit a mutation for changing networkBusyStatus to false when all requests have been resolved
  })
}

vuexModule.js

const store = new Vuex.Store({
  state: {
    networkStatusBusy: false // you can share networkStatusBusy state so that when multiple api calls are made on  the same component, networkStatusBusy doesn't return to false until all calls are resolved.
    data: [],
    otherAsyncData: [],
  },
  mutations: {
    loading (state, payload) {
      state.networkStatusBusy = payload
    }
    setAsyncData(state, payload) {
      state.data = payload;
    }
    setOtherAsyncData(state, payload) {
      state.otherAsyncData = payload;
    }
  }
  actions: {
    fetchAsyncData ({ commit }) {
      axios.get('path-to-api').then(result => {
        commit ('setAsyncData', result.data)
      })
    }
    fetchAnotherAsyncDataOnTheSameComponent ({ commit }) {
      axios.get('another-api-on-same-component').then(result => {
        commit('setOtherAsyncData', result.data);
      })
    }
  }

})

.vue 文件

import { mapState } from 'vuex';
export default {
  // ...
  computed: mapState({
    networkBusyStatus: state => state.(moduleInQuestion).networkBusyStatus,
  }),
  watch: {
    networkBusyStatus function (newVal, oldVal) {
      console.log('new value', newVal)
    }
  }
}

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多