在这个例子中,我使用axios为我提取一些数据,然后我需要传递这些值并将其存储在Vuex中
带有axios请求的vue文件:
<script>
export default {
data: function () {
return {
userData: {},
login: {
username: '',
password: '',
},
}
},
computed: {
loggedInUser() {
return this.$store.state.loggedInUser;
}
},
methods: {
handleLoginFormSubmit() {
// send axios request to controller and from controller to gRPC
axios.post('/loginUser', this.login)
.then((response) => {
this.userData = JSON.parse(response.data[0]);
})
// set loggedInUser info to vuex store
this.$store.dispatch('loginUser',this.userData);
}
},
}
</script>
当我检查userData对象时,我需要所有信息 现在我有store.js文件应该传递该userData并将其保存在Store中,但我总是得到空对象
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
loggedInUser: {
firstName: '',
lastName: '',
email: '',
uuid: '',
}
},
getters: {
loggedUser(state){
return state.loggedInUser;
}
},
mutations: {
loginUser: (state, payload) => {
state.loggedInUser.firstName = payload;
state.loggedInUser.lastName = 1;
state.loggedInUser.email = 1;
state.loggedInUser.uuid = 1;
}
},
actions: {
loginUser: (context, payload) => {
setTimeout(function () {
console.log(payload);
context.commit('loginUser', payload)
}, 3000)
}
}
});
我的突变看起来像这样
输入:“loginUser”
有效负载:对象(空)
我在哪里做错了什么?
答案 0 :(得分:5)
您在数据返回之前发送。将调度移动到回调中。
%put &=date &=sno &=no;