Javascript Vue-在分派完成后调用存储getter?
我使用的是Laravel5.7+Vue2+Vuex 在分派调用完成后,我很难让Vue返回存储值。我的应用程序流如下所示:Javascript Vue-在分派完成后调用存储getter?,javascript,vue.js,vuejs2,vue-component,vuex,Javascript,Vue.js,Vuejs2,Vue Component,Vuex,我使用的是Laravel5.7+Vue2+Vuex 在分派调用完成后,我很难让Vue返回存储值。我的应用程序流如下所示: 我单击一个submit按钮,该按钮在组件上调用validate() Validate()分派给我的“addLease”操作,该操作调用Laravel控制器中的store api Laravel验证数据并返回带有错误的响应或成功消息 然后执行提交以使用适当的值(或错误,如果表单验证失败)更新leaseStore状态 我所面临的问题是,我只是提交空白表格,所以显然有错误被返回,我
我所面临的问题是,我只是提交空白表格,所以显然有错误被返回,我可以在Chrome DEV工具的网络选项卡中看到。在将错误存储到leaseStore状态之前,一切似乎都很正常。我在控制台中收到以下错误:
Uncaught (in promise) TypeError: Cannot read property 'leaseStore' of undefined
我可能错过了一些小的东西,但我不知道我错在哪里。我认为在尝试将错误值提交到leaseStore状态时可能会出现问题,但我不确定
API调用:
postLeaseStore: function(data){
return axios.post('/api/lease',
data
);
}
addLease({ commit, state }, data) {
commit('setLeaseStore', 0);
LeaseAPI.postLeaseStore(data)
.then( function( response ) {
console.log('Success');
commit('setLeaseStore', 1);
})
.catch( function(error) {
console.log('Error');
return commit('setLeaseStore', 3);
});
}
computed: {
leaseStore() {
return this.$store.getters.getLeaseStore;
}
},
methods: {
validate()
{
this.$store.dispatch('addLease', this.input).then(function () {
console.log(this.leaseStore);
});
}
}
行动:
postLeaseStore: function(data){
return axios.post('/api/lease',
data
);
}
addLease({ commit, state }, data) {
commit('setLeaseStore', 0);
LeaseAPI.postLeaseStore(data)
.then( function( response ) {
console.log('Success');
commit('setLeaseStore', 1);
})
.catch( function(error) {
console.log('Error');
return commit('setLeaseStore', 3);
});
}
computed: {
leaseStore() {
return this.$store.getters.getLeaseStore;
}
},
methods: {
validate()
{
this.$store.dispatch('addLease', this.input).then(function () {
console.log(this.leaseStore);
});
}
}
Vue组件:
postLeaseStore: function(data){
return axios.post('/api/lease',
data
);
}
addLease({ commit, state }, data) {
commit('setLeaseStore', 0);
LeaseAPI.postLeaseStore(data)
.then( function( response ) {
console.log('Success');
commit('setLeaseStore', 1);
})
.catch( function(error) {
console.log('Error');
return commit('setLeaseStore', 3);
});
}
computed: {
leaseStore() {
return this.$store.getters.getLeaseStore;
}
},
methods: {
validate()
{
this.$store.dispatch('addLease', this.input).then(function () {
console.log(this.leaseStore);
});
}
}
您正在失去回调中此(Vue实例)的作用域,要修复此问题,请使用箭头函数
()=>
,如:
methods: {
validate()
{
this.$store.dispatch('addLease', this.input).then(()=> {
console.log(this.leaseStore);
});
}
}
您正在失去回调中此(Vue实例)的作用域,要修复此问题,请使用箭头函数
()=>
,如:
methods: {
validate()
{
this.$store.dispatch('addLease', this.input).then(()=> {
console.log(this.leaseStore);
});
}
}
只需使用箭头函数,比如
this.store.dispatch('addLease',this.input.),然后(()=>{console.log(this.leaseStore);})代码>是!!哇!这样一个简单的解决方案,我甚至在复制和粘贴时都没有注意到。非常感谢。只需使用箭头函数,比如this.store.dispatch('addLease',this.input.),然后(()=>{console.log(this.leaseStore);})代码>是!!哇!这样一个简单的解决方案,我甚至在复制和粘贴时都没有注意到。非常感谢。