是否有#34;承诺"从组件内部调用的vuex dispatch上的行为类型?

时间:2017-12-03 16:34:10

标签: javascript vue.js promise axios vuex

我正在学习vuex并且遇到这个问题,在created()上我想从API获取数据然后一旦完成,我想从组件调用getter并将getter卡分配给组件的卡。我在created()中添加了一条注释,这样你就可以看到我想要的内容。是否有#34;承诺"派遣行为的类型?完成后做一些事情。提前致谢。我附上了代码截图。

组件:

    <template>

     <div class="container" :class="{'is-loading': isLoading}">
       <h1>All Cards</h1>
       <hr>
        <section class="columns">
          <app-card :card="card" v-for="card in cards" key="asdasd" />

        </section>
     </div>
   </template>


<script>
import axios from 'axios'
import AppCard from './AppCard'

export default {
  name: 'AppCards',
  components: {
    AppCard
  },
  data () {
    return {
      isLoading: true,
      endpoint: `/cards.json`,
      cards: []
    }
  },

  created() {
    this.$store.dispatch('fetchAllCards', this.endpoint) 
      // then(() => {
      //  this.cards = this.$store.getters.allCards  (I want to get cards once action / mutation did its job and assign to this component's cards )
      // }) 

  }
}
</script>

Vuex:

import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import axios from 'axios'

Vue.use(Vuex)


const state = {
    cards: null
}


const mutations = {
    storeCards(state, fetchedCards) {
        state.cards = fetchedCards
    }
}


const actions = {
    fetchAllCards({commit, state}, payload) {

        axios.get(payload)
          .then(response => {
            const data = response.data
            const cards = []

            for(let key in data) {
              if(data[key] !== null) {
                const card =  data[key]
                card.id = key
                cards.push(card)
              }
            }

            commit('storeCards', cards)

          })
          .catch(e => {
            console.log(e)
          })

    }
}


const getters = {
    allCards(state) {
        return state.cards
    }
}


export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})

1 个答案:

答案 0 :(得分:1)

与此同时,我在Vue的聊天中得到了答案,所以万一有人碰到这个问题,这就是答案

商店内

修改后的操作:

const actions = {
  fetchAllCards({ commit }, payload) {
    // return is here so we can use than inside comp (returns a promise)
    return axios.get(payload).then( ({ data }) => {
    const cards = [];
    for(let key in data) {
      if(data[key] !== null) {
        const card =  data[key]
        card.id = key
        cards.push(card)
      }
    }
    commit('storeCards', cards)
  })
}

修改created()并计算获取组件内的项目:

computed: {
  cards() {
    return this.$store.getters.allCards
  }
},


created() {
  this.$store.dispatch('fetchAllCards', this.endpoint) .then(() => {
    this.isLoading = false
  })
}