如何使用mapActions获取数据

时间:2018-12-28 12:59:06

标签: vue.js axios vuex

我似乎无法从商店使用mapActions获得所需的数据。我正在执行Axios GET(将数据转换为数组),并将该数据传递到home.vue,并呈现注释列表。 现在,如果我使用mapGetters可以正常工作,但是据我了解,我可以直接从mapActions访问数据,我见过有人这样做,但到目前为止我还不能。可以吗

Home.vue:

  export default {
  methods:{
    // Not Working
    ...mapActions(
        ['getNotes']
    ),
    created(){
    // Not working
    this.getNotes()
    console.log(this.getNotes())//returns pending Promise
  }
}

我的store.js

export default new Vuex.Store({
  state: {
    ...other stuff in state...
    // this is getting the notes from firebase
    notes: {}
  },
  getters: {
    ...other getters...
    notes: state => state.notes
  },
  mutations: {
    ...other mutations...
    SET_NOTES (state, notes) {
      state.notes = notes
    }
  },
  actions: {
    getNotes ({ commit }) {
      axios.get('/data.json')
        .then(res => {
          const incoming = res.data
          const notes = [] // <-- this is commited ok without explicit return
          // converting object to array
          // extracting firebase ids for manipulating existing notes
          for (let key in incoming) {
            const note = incoming[key]
            note.id = key
            notes.push(note)
          }
          console.log(notes)
          commit('SET_NOTES', notes)
          // return notes <-- tried that, no effect!
        })
        .catch((error) => {
          console.log('Error: ', error)
        })
    },
    ...commiting 2 other things needed for my app
  }
  ...other actions...
})

1 个答案:

答案 0 :(得分:0)

我看不到您在操作getNotes()中将笔记数据作为返回值返回。在成功回调的最后,您要做的就是将数据提交到注释commit('SET_NOTES', notes)中。

  

返回笔记数据

getNotes ({ commit }) {
  axios.get('/data.json')
    .then(res => {
      const incoming = res.data
      const notes = []
      // converting object to array
      // extracting firebase ids for manipulating existing notes
      for (let key in incoming) {
        const note = incoming[key]
        note.id = key
        notes.push(note)
        // array.reverse()
      }
      console.log(notes)
      commit('SET_NOTES', notes)
      // HERE YOU RETURN YOUR NOTES DATA
      return notes
    })
    .catch((error) => {
      console.log('Error: ', error)
    })
}