我的商店里有以下内容:
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
仍为空。请问,我做得不对?
在我的组件方法中,我调用了这样的突变:
markAsCurrent (campaign) {
this.$store.commit('CURRENT_CAMPAIGN', campaign.id)
}
但currentCampaign
状态正在返回undefined
答案 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}