事件永远不会在axios调用中的VueJS中发出

时间:2019-07-31 09:09:39

标签: javascript vuejs2

我有一个需要在开始时初始化数据的组件,它会对数据进行一些转换(基于一些保存在本地存储中的值,以将这些数据标记为选中状态)。

使用Vue 2.5。

// component.vue

import Vue from 'vue'

export default Vue.extend({
  data() {
    fetchedData: [],
  },

  mounted() {
    this.getStuff()

    window.Bus.$on('localStorageRefreshed', this.getStuff)
  },

  computed: {
    selectedData() {
      return this.fetchedData.filter(data => data.selected)
    }
  },

  methods: {
    getStuff() {
      const doTransformations = function (res, existing) {
        // blabla
      }

      axios.get('/endpoint/for/stuff/').then(result => {
        doTransformations(result, this.fetchedData) // not exactly what happens, but I think this is unneeded to solve my problem. mostly there to illustrate how this all fits together.
        window.Bus.$emit('stuffFetched', this.selectedData)
      })
    },
  }
})

所以window.Bus是一个Vue实例,它只是冒充全局事件处理程序。在我的getStuff方法中,该事件永远不会发出,我也不知道为什么。我已经在所有地方登录了控制台,以便弄清总线是否尚未初始化(这是因为我有很多可以很好地使用它的组件)。该事件永远不会发出。我曾尝试将发光包装在$nextTick中,但是那也不起作用(我也尝试直接在mounted-lifecycle方法中进行此处理,因为Vue devtools中的计算属性应该像这样并且包含所有正确的内容。

我真的很茫然,这里的一切似乎都应该按预期进行,但是该事件甚至没有在Vue devtools中注册。

我需要触发该事件的原因是为了对存在于此子级及其父级范围之外的另一个组件进行一些价格计算。使用此方法,仅在子范围(this.$emit('dataChanged'))中发出也不会发出事件。

有人知道我的******大脑在这里对我做什么吗?

1 个答案:

答案 0 :(得分:1)

您尝试使用异步等待吗? 我可能会做超时工作,例如:

async mounted() {
  await this.getStuff()

  window.Bus.$on('localStorageRefreshed', this.getStuff)
}

,然后在您的getStuff上执行该操作:

async getStuff() {
  const doTransformations = function (res, existing) {
    // blabla
  }

  await axios.get('/endpoint/for/stuff/').then(result => {
      doTransformations(result, this.fetchedData) // not exactly what happens, 
           but I think this is unneeded to solve my problem. mostly there to 
           illustrate how this all fits together.
    window.Bus.$emit('stuffFetched', this.selectedData)
  })
}