Vue js2 vuex update a form v-model values



我已经设置了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 中获取数据。

我哪里错了。

注意:AM使用数据更新这样的表单

<input  v-model="profile_form.email" >

挂载的方法需要从 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)
  }
},

最新更新