Vue:vuex模块中的组件方法?

时间:2019-05-01 12:39:34

标签: javascript vue.js

我在vuex中使用命名空间模块进行状态管理,我尝试将所有动作突变保留在模块内,因为这有助于我将大部分代码保持在同一位置(模块的作用类似于类或类似内容),问题,我想在vuex操作成功时(即axios请求获得OK / 200响应)触发一种组件方法来清除表单,但可悲的是,我无法从vuex模块向我的组件触发一种方法(没有这个inisde模块)。

我还尝试将.then添加到我的动作调用中,但是在我调用动作后立即触发...

我想我可以将动作移到组件本身中,但是我不愿意,你们有什么建议?

我的组件

stripeSourceHandler: function(sourceId)
    {
        if(this.customerSources.length == 0)
        {
            console.log('createSourceAndCustomer');
            this.createSourceAndCustomer({ id: sourceId });
        }
        else
        {
            console.log('addSource');
            this.addSource({ id: sourceId }).then(alert('Form cleared')); //this fires right after calling addSource
        };
    },

我的模块操作:

addSource({ commit }, sourceId)
    {
        commit('Loader/SET_LOADER', { status:1, message: 'Procesando...' }, { root: true });
        axios.post('/stripe/add-source', sourceId)
        .then((response) => {
            commit('Loader/SET_LOADER', { status:2, message: response.data.message }, { root: true });
            commit('ADD_SOURCE', response.data.customer);
            //I can't clear component form from this...
        }, 
        (error) => {
            commit('Loader/SET_LOADER', { status:3, errors: error, message: 'Error al añadir el pago.' }, { root: true });
        });
    },

1 个答案:

答案 0 :(得分:0)

两个问题:

  • 您需要从操作中返回承诺,以便您可以使用.then()来安排操作完成后要执行的代码(此代码是清除表单所需的操作)。
  • .then()使用一个(或两个)功能作为参数,一旦承诺解决,这些参数将被调用,相反,您只是立即调用alert()

会是这样的:

组成方法

stripeSourceHandler(sourceId) {
  if (this.customerSources.length == 0) {
    this.createSourceAndCustomer({ id: sourceId });
  } else {
    this.addSource({ id: sourceId }).then(() => {
      // Clear the form here
      alert('Form cleared');
    });
  }
}

Vuex操作

addSource({ commit }, sourceId) {
  commit('Loader/SET_LOADER', { status:1, message: 'Procesando...' }, { root: true });

  // Return the promise here
  return axios.post('/stripe/add-source', sourceId)
    .then(response => {
      commit('Loader/SET_LOADER', { status:2, message: response.data.message }, { root: true });
      commit('ADD_SOURCE', response.data.customer);
    }, error => {
      commit('Loader/SET_LOADER', { status:3, errors: error, message: 'Error al añadir el pago.' }, { root: true });
    });
}