Vue - 分派完成后调用商店 getter? [英] Vue - Calling store getter after dispatch completes?

查看:33
本文介绍了Vue - 分派完成后调用商店 getter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Laravel 5.7 + Vue2 + Vuex

I'm using Laravel 5.7 + Vue2 + Vuex

在我的调度调用完成后,我很难让 Vue 返回存储值.我的申请流程如下所示:

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

  1. 我单击了一个提交按钮,该按钮在组件上调用了 validate().
  2. Validate() 分派到我的addLease"操作,该操作调用 Laravel 控制器中的商店 API.
  3. Laravel 验证数据并返回包含错误或成功消息的响应.
  4. 然后执行提交以使用适当的值(或错误,如果表单验证失败)更新leaseStore 状态.

我遇到的问题是我只提交了空白表单,所以很明显返回了错误,我可以在 Chrome DEV 工具的网络选项卡中看到这些错误.在将错误存储在leagueStore 状态之前,一切似乎都正常.我在控制台中收到以下错误:

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

我可能遗漏了一些小东西,但我不知道我哪里出错了.我认为在尝试将错误值提交到leagueStore 状态时可能会出现问题,但我不确定.

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 调用:

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

行动:

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 组件:

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

推荐答案

您在回调中丢失了 this(Vue 实例)的范围,以修复使用箭头函数 ()=> 像:

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

这篇关于Vue - 分派完成后调用商店 getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆