吸气剂未按预期返回值

时间:2020-05-01 23:45:23

标签: vue.js vuex

为什么打给我

getters.getEventById(id)

我打电话时的方式不一样

state.events.find(event => event.id === id)

在两个console.log上查看关于fetchEvent操作的开头。

  fetchEvent({ commit }, id) {
    var event = getters.getEventById(id)
    console.log(event)
    console.log(state.events.find(event => event.id === id))
    if (event) {
      commit('SET_EVENT', event)
    } else {
      EventService.getEvent(id)
        .then(response => {
          commit('SET_EVENT', response.data)
        })
        .catch(error => {
          console.log(error.response)
        })
    }
  }
}

export const getters = {
  getEventById: state => id => {
    return state.events.find(event => event.id === id)
  }
}

结果是:

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码段中似​​乎缺少一些代码:fetchEvent如何访问stategetters?通常,Vuex actions会通过第一个参数接收stategetters

我接受了您的代码,将其放在一个简单的Vuex样板中,对其进行了一些重构,它可以按您期望的那样工作。

Vue.component('event', {
  template: '<div></div>',
  created() {
    this.$store.dispatch('fetchEvent', 1);
  },
});

const store = new Vuex.Store({
  state: {
    events: [{
        id: 1
      },
      {
        id: 2
      },
      {
        id: 3
      },
    ]
  },
  actions: {
    fetchEvent({
      commit,
      state,
      getters,
    }, id) {
      var event = getters.getEventById(id)
      console.log('getter:', event)
      console.log('local find:', state.events.find(event => event.id === id))
    }
  },
  getters: {
    getEventById: state => id => {
      return state.events.find(event => event.id === id)
    }
  }
})

const app = new Vue({
  store,
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
  <event></event>
</div>