组件中的数据
data() {
return {
searchForm: [{
label: 'Name',
subItems: []
}]
}
}
actions方法
const actions = {
getDimensions({ commit }, param) {
api.getDimensions(param).then(res => {
commit(types.GET_DIMENSIONS, res.data);
});
}
}
const mutations = {
[types.GET_DIMENSIONS](state, dimensions) {
state.dimensions = dimensions;
}
}
注意下面的输出语句,输出的时候有时候输出空,有时候输出后台传过来的数据,我觉得原因应该是this.$store.dispatch('getDimensions', param);是异步请求,在输出的时候,this.$store.getters.dimensions的值还没有取到,所以为空。请问这样理解对吗?
methods: {
getDimensions() {
let param = {
type: 2
}
this.$store.dispatch('getDimensions', param);
console.log(this.$store.getters.dimensions);
}
}
后来,我改成了这种形式
methods: {
getDimensions() {
let param = {
type: 2
}
this.$store.dispatch('getDimensions', param)
.then(res => {
console.log(res);
console.log(this.$store.getters.dimensions);
});
}
}
这时,输出的res一直为undefined,this.$store.getters.dimensions有时候为空,有时候又输出后台的数据,这是为什么呢?
我先在想做的就是将this.$store.getters.dimensions赋值给this.searchForm[0].subItems
异步处理放在 action 中没有问题,问题是你需要在异步回调后,去 commit 修改,然后 return promise 出来,通过 then 监听。
还有就是如果对数据有依赖监听,用 watch 啊。