我正在尝试创建基于Vue.js的应用。这是我的情况。我有一个组件,其中有一个弹出窗口可用于创建“费用”条目。当单击“保存”按钮时,我调用Vuex模块中定义的函数,该函数处理api调用以保存条目。像这样
import { mapActions } from 'vuex';
export default {
name : 'CreateExpense',
data(){
return {
expense : {
expense : null,
amount : 0,
comment : null
}
}
},
methods : {
...mapActions(['addExpense']),
saveExpense(){
this.addExpense( this.expense );
}
}
}
我的vuex模块有这个
const actions = {
addExpense({commit},expense){
axios.post( env.API_URL + 'save-expense',expense)
.then( response => commit('addExpense',expense) )
}
};
我的问题是我无法弄清楚如何将信息传递到此api调用已完成并且费用状态对象已更新的组件,以便它可以关闭在那里打开的弹出窗口。我希望.catch / .then在模块本身而不是组件中处理,而在组件中,只需关闭弹出窗口+一些警报消息即可。请为我指明方向
答案 0 :(得分:0)
import { mapActions, mapGetters } from 'vuex';
export default {
name : 'CreateExpense',
data(){
return {
expense : {
expense : null,
amount : 0,
comment : null
}
}
},
methods : {
...mapActions(['addExpense']),
saveExpense(){
this.addExpense( this.expense );
}
},
computed: {
...mapGetters(['expense'])
},
watch: {
expense (val) {
if (val) //close popup modal
}
}
}
store.js
export default new Vuex.Store({
actions: { ... },
state: { ... },
getters: {
expense: ({expense}) => expense
}
}
答案 1 :(得分:0)
或者(没有mapGetters)
在您的商店中:
addExpense ({commit}, expense) {
return new Promise ((resolve, reject) => {
axios.post(env.API_URL + 'save-expense', expense)
.then(response => {
commit('addExpense', expense);
resolve(response); // THIS WILL RETURN TO YOUR COMPONENT
})
.catch(err => {
reject(err);
})
})
}
在您的组件中:
mounted: function () {
this.myMethod()
},
methods: {
myMethod: function () {
this.$store.dispatch('addExpense')
.then(response => {
console.log('response', response) // SHOULD GET VALUE FROM RESOLVE
})
}
}