Vue - Calling store getter after dispatch completes?

烂漫一生 提交于 2021-01-29 06:57:47

问题


I'm using Laravel 5.7 + Vue2 + Vuex

I am having some difficulty getting Vue to return a store value after my dispatch call completes. My application flow looks like this:

  1. I click a submit button which calls validate() on the component.
  2. Validate() dispatches to my "addLease" action which calls the store api in a Laravel controller.
  3. Laravel validates the data and returns a response with errors, or a success message.
  4. A commit is then performed to update the leaseStore state with the appropriate value (or error, if form validation fails).

What I'm having issues with is I'm submitting just the blank form so obviously there are errors being returned which I can see in the Network tab of Chrome DEV tools. Everything seems to work fine until it comes to storing the errors in the leaseStore state. I receive the following error in the console:

Uncaught (in promise) TypeError: Cannot read property 'leaseStore' of undefined

I'm probably missing something small but I can't figure out where I'm going wrong. I think there might be an issue when trying to commit the error value to the leaseStore state, but I'm not sure.

API Call:

postLeaseStore: function(data){
    return axios.post('/api/lease',
        data
    );
}

Action:

addLease({ commit, state }, data) {
    commit('setLeaseStore', 0);

    LeaseAPI.postLeaseStore(data)
    .then( function( response ) {
        console.log('Success');
        commit('setLeaseStore', 1);
    })
    .catch( function(error) {
        console.log('Error');
        return commit('setLeaseStore', 3);
    });
}

Vue Component:

computed: {
    leaseStore() {
        return this.$store.getters.getLeaseStore;
    }
},
methods: {
    validate()
    {
        this.$store.dispatch('addLease', this.input).then(function () {
            console.log(this.leaseStore);
        });
    }
}

回答1:


You're losing the scope of this (Vue instance) inside your callback, to fix that use arrow function ()=> like :

    methods: {
     validate()
       {
       this.$store.dispatch('addLease', this.input).then(()=> {
        console.log(this.leaseStore);
      });
     }
   }


来源:https://stackoverflow.com/questions/54525205/vue-calling-store-getter-after-dispatch-completes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!