我已经设置了vuex,我想稍后获取数据并更新我的表单模型,但这失败了
在我的vuex
//state
const state = {
profile: [],
}
//getter
const getters = {
profileDetails: state => state.profile,
}
//the actions
const actions = {
getProfileDetails ({ commit }) {
axios.get('/my-profile-details')
.then((response) => {
let data = response.data;
commit(types.RECEIVED_USERS, {data});
},
);
}
}
const mutations = {
[types.RECEIVED_USERS] (state, { data }) {
state.profile = data;
state.dataloaded = true;
},
}
现在在我的vue js文件中
export default{
data: () => ({
profile_form:{
nickname:'',
first_name:'',
last_name:'',
email:''
}
}),
computed:{
...mapGetters({
user: 'profileDetails',
}),
},
methods:{
setUpDetails(){
this.profile_form.email = this.user.email; //the value is always undefined
}
},
mounted(){
this.$store.dispatch('getProfileDetails').then(
(res)=>{
console.log(res); //this is undefined
this.setUpDetails(); ///this is never executed
}
);
this.setUpDetails(); //tried adding it here
}
通过使用vue开发人员工具检查,我可以看到vuex有数据但我的组件在调用操作中的调度以获取数据后无法在vuex中获取数据 .
我哪里错了 .
Nb:AM使用数据来更新这样的表单
<input v-model="profile_form.email" >
1 回答
您的挂载方法需要从
getProfileDetails
返回(res),但操作不会返回任何内容,因此您可以尝试但是,更常见的是从动作(你正在做)中提交存储并让组件从getter(你有)获得新值 - 即单向数据流 .
这就是我设置它的方式 .