所以我有一个有价值的商店:
export const store = new Vuex.Store({
state: {
selectedGradeId: null,
},
getters:{
selectedGradeId: state => {
return state.selectedGradeId
},
},
mutations:{
SET_SELECTED_GRADE_ID(state, gradeid){
state.selectedGradeId = gradeid
},
CLEAR_SELECTED_GRADE_ID(state){
state.selectedGradeId = null
},
},
actions:{
loadStudentsForGrade (gradeId) {
return new Promise((resolve, reject) => {
axios.get('/students/'+gradeId)
.then((response)=>{
... do stuff
resolve(response)
}, response => {
reject(response)
})
})
},
}
})
在我的组件内部我基本上有一个选择加载特定年级的学生列表:
<select id="grades" name="grades" v-model="selectedGradeId" @change="loadStudentsForGrade(selectedGradeId)"
methods: {
loadStudentsForGrade(gradeId) {
this.$store.dispatch('loadStudentsForGrade', {gradeId})
.then(response => {
}, error => {
})
},
},
computed: {
selectedGradeId: {
get: function () {
return this.$store.getters.selectedGradeId;
},
set: function (gradeId) {
this.$store.commit('SET_SELECTED_GRADE_ID', gradeId);
}
},
}
当在我的组件中调用'loadStudentsForGrade'方法时,它将'selectedGradeId'作为参数,这是一个计算属性。 现在我遇到的问题是,在我的商店内,动作'loadStudentsForGrade'得到一个对象(我猜是计算?)而不仅仅是theidid
我得到的对象打印到控制台: {dispatch:ƒ,commit:ƒ,getters:{...},state:{...},rootGetters:{...},...}
答案 0 :(得分:0)
您的操作的第一个参数是商店,第二个参数是有效负载。 所以你应该这样做:
actions:{
// here: loadStudentsForGrade (store, payload) {
loadStudentsForGrade ({ commit }, { gradeId }) {
return new Promise((resolve, reject) => {
axios.get('/students/'+gradeId)
.then((response)=>{
//... do stuff
//... commit('', response);
resolve(response)
}, response => {
//... commit('', response);
reject(response)
})
})
},
}
文档中的相关页面: https://vuex.vuejs.org/en/actions.html#dispatching-actions