Vuex操作对象不返回数据

时间:2018-03-07 18:47:30

标签: vue.js vuex

我的商店里有以下内容:

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex);

export const store = new Vuex.Store({
state: {
    campaigns: '',
    currentCampaign: null
},

mutations: {
    GET_CAMPAIGNS(state, campaigns) {
        state.campaigns = campaigns
    }
},
actions: {
    getCampaigns ( context ) {
       return axios
            .get('/api/campaign/history')
            .then((response) => {
                context.commit('GET_CAMPAIGNS', response.data)
            })
    },
}

});

问题是campaigns仍为空。请问,我做得不对?

dev tool snapshot

Current campaign

在我的组件方法中,我调用了这样的突变:

markAsCurrent (campaign) {
            this.$store.commit('CURRENT_CAMPAIGN', campaign.id)
        } 

currentCampaign状态正在返回undefined

2 个答案:

答案 0 :(得分:1)

由于您使用的是actions而非mutations来检索数据,因此您应该使用dispatch()函数而不是commit()函数。

实际上,我希望您从axios.get()拨打methods而不是store本身。

markAsCurrent (campaign) {
  let campaigns

  axios.get('/api/campaign/history').then(response => {
    campaigns = response.data
  }

 this.$store.dispatch('getCampaigns', campaigns)
}
actions: {
 getCampaigns ({commit}, campaigns) {
    commit('GET_CAMPAIGNS', campaigns)
  }
}

答案 1 :(得分:0)

  

将您的操作更改为以下代码:

getCampaigns ( {commit}, context ) {
      axios.get('/api/campaign/history')
        .then((response) => {
            context.commit('GET_CAMPAIGNS', response.data)
        })
}
  

然后你必须从你的组件中调用这个动作,如下所示:

this.$store.dispatch('getCampaigns', passTheDataHere)
  

注意:如果你想在动作中提交变异,你必须在参数中使用{commit}。如果你想使用状态或getter那么{commit,getters,state}