2017-10-07 45 views
0

我已经安装vuex,我想在以后获取数据,并更新自己的状态的模式,但这种失败Vue的JS2 vuex更新,形式V-模型值

在我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数据检查。

我在哪里出错了。

注:我使用的数据来更新这样

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

然而,这是更常见的承诺与行动(你正在做的)内存储,让成分得到一个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) 
    } 
},