【问题标题】:Vue js2 vuex update a form v-model valuesVue js2 vuex 更新表单 v-model 值
【发布时间】:2017-10-07 21:04:21
【问题描述】:

我已经设置了 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 有数据,但我的组件在调用 action 中的 dispatch 以获取数据后无法在 vuex 中获取数据。

我哪里错了。

Nb:AM 使用数据来更新这样的表单

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

【问题讨论】:

    标签: javascript vuejs2 vuex


    【解决方案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)
      }
    },
    

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 2022-10-24
      • 2019-11-09
      • 2020-06-29
      • 2017-04-16
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多