2017-10-07 6 views
0

値Iがセットアップvuexを持っていると私は後でデータを取得し、私のフォームモデルを更新したいと思いますが、これが今の私のvuexVueのJS2 vuex形態V-モデルは

//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; 
    }, 

} 

を失敗した更新私はvuexがデータを持っていますが、私のコンポーネントは、データをフェッチするために、アクションでの発送を呼び出した後vuexでデータをフェッチ傾けることがわかりますVUEの開発ツールでチェックすることにより、私の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 
    } 

どこが間違っていますか。

のNb:

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

答えて

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 
     }, 
    ); 
    } 
    } 

しかし、それは(あなたがやっている)アクション内から保存し、コンポーネントは(あなたが持っている)ゲッターから新しい値を取得できるようにコミットするより一般的だ - 片道 - データフロー、すなわち、 。

これは私がそれを設定する方法です。

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) 
    } 
},