我已经设置了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有数据但我的组件在调用动作中的调度后才能获取数据。
我哪里出错。
Nb:AM使用数据来更新这样的表格
<input v-model="profile_form.email" >
答案 0 :(得分:1)
您的挂载方法需要getProfileDetails
的返回(res),但操作不会返回任何内容,因此您只需尝试
const actions = {
getProfileDetails ({ commit }) {
return axios.get('/my-profile-details')
.then((response) => {
let data = response.data;
commit(types.RECEIVED_USERS, {data});
return data // put value into promise
},
);
}
}
然而,更常见的是承诺从动作中存储(你正在做)并让组件从getter(你有)获取新值 - 即单向数据 - 流。
我就是这样设置的。
data: () => ({
profile_form:{
nickname:'',
first_name:'',
last_name:'',
email:''
}
}),
mounted(){
this.$store.dispatch('getProfileDetails')
}
computed: {
...mapGetters({
user: 'profileDetails',
}),
}
watch: {
user (profileData){
this.profile_form = Object.assign({}, profileData);
}
},
methods:{
submit(){
this.$store.commit('submituser', this.profile_form)
}
},