我想实现一个登录方法。我的代码是:
login() {
let user = {
email: this.email,
password: this.password
};
this.$store.dispatch('auth/login', user)
console.log(this.$store.getters['auth/getAuthError'])
},
我到达商店并调度登录操作。
商店中的操作如下:
login(vuexContext, user) {
return axios.post('http://localhost:8000/api/user/login', user)
.then(res => {
vuexContext.commit('setToken', res.data.token)
vuexContext.commit('setUser', res.data, {root: true})
localStorage.setItem('token', res.data.token)
Cookie.set('token', res.data.token )
this.$router.push('/')
}).catch(err => {
vuexContext.commit('setAuthError', err.response.data)
})
},
在catch块中,如果发生错误,我将更新状态并将authError
属性设置为我得到的错误。
我的问题是,在登录方法中,console.log
语句是在操作实际完成之前执行的,因此authError
属性是尚未设置的状态。
如何解决此问题?
答案 0 :(得分:3)
您的
action
是返回一个promise
,因此您可以控制台 承诺已在then()
区块中解决。
login() {
let user = {
email: this.email,
password: this.password
};
this.$store.dispatch('auth/login', user).then(() => {
console.log(this.$store.getters['auth/getAuthError'])
// this.$router.push('/') // Also, its better to invoke router's method from a component than in a store file, anyway reference of a component may not be defined in the store file till you explicity pass it
})
},
或者,您可以将 login 设为
async
函数,并将wait
的{{1}}设为 promise 操作返回的问题已已解决
action
答案 1 :(得分:2)
您可以使用 async-await 而不是 Promise.then 。但是我的建议是不要在商店内使用Axios。在登录方法中调用Axios,然后调用商店。像这样:
System::Runtime::InteropServices::Marshal::Copy( IntPtr( ( void * ) sourcePointer), targetManagedArray, 0, dataSize );
然后您只需要在商店中设置对象。