[英]Vuex getter returns null
I am creating a simple user login system with vue and vuex.我正在使用 vue 和 vuex 创建一个简单的用户登录系统。 My problem is when I want to reach error state that in my store, it returns null.
我的问题是当我想在我的商店中遇到错误 state 时,它返回 null。 But if I add a timeout on that, it returns what I want.
但是,如果我对此添加超时,它会返回我想要的。 I added a console.log message in the mutation section, and also I added console log in my component method.
我在突变部分添加了一条 console.log 消息,还在我的组件方法中添加了控制台日志。 Output looks like;
Output 看起来像;
Mutation comes after component.突变出现在组件之后。
My store;我的商店;
const state = {
error: null
};
const getters = {
getError: state => state.error,
};
const actions = {
login({ commit }, user) {
axios.post('http://localhost:3000/api/users/login', user).then(res => {
//User auth part
})
.catch(err => { //I am committing to mutation
commit('auth_error', err.response.data);
return err.response.data;
});
}
};
const mutations = {//I am mutating my error state
auth_error(state, err) {
console.log('MUTATION MESSAGE:', err);
state.error = err;
},
};
My component looks like;我的组件看起来像;
import { mapActions, mapGetters } from "vuex";
export default {
computed:{
...mapGetters(['getError']),
},
methods: {
...mapActions(["login"]),
loginUser() {
const user = {
username: this.username,
password: this.password,
};
this.login(user)//I am calling my store's method
.then((res) => {
if (!res.data.error) {
console.log("Success");
} else {
console.log(res.data.message);
}
})
.catch((err) => {//Here is my problem
console.log('COMPONENT MESSAGE', this.getError);
setTimeout(() => {//If i add timeout, it works.
this.error = this.getError;
}, 500);
});
},
},
};
Please tell me if there are missing parts that needed.请告诉我是否缺少需要的零件。
You need to return the http promise from your action:您需要从您的操作中返回 http promise:
login({ commit }, user) {
return axios.post('http://localhost:3000/api/users/login', user).then(res => {
//User auth part
})
.catch(err => { //I am committing to mutation
commit('auth_error', err.response.data);
return err.response.data;
});
}
Now you can properly chain .then
from the promise in the component.现在您可以从组件中的 promise 正确链接
.then
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.