从服务文件调度突变

Dispatch mutations from service file

我有一个 ApiService(),我正在将我的 API 调用抽象到其中。我想 dispatch('SET_BUSY')dispatch('SET_NOT_BUSY') 来自内部的应用级突变 服务,但出现以下错误:

TypeError: dispatch is not a function. (In 'dispatch('SET_BUSY')', 'dispatch' is undefined)

/vuex/actions.js

import { ApiService } from './services';

export const setAppMode = function ({ dispatch }) {
  ApiService({
    noun: 'Application',
    verb: 'GetMode'
  }, response => {
    dispatch('SET_APP_MODE', response.Data.mode);
  },
  dispatch);
};

/vuex/services.js

import Vue from 'vue';

export const ApiService = (options = {}, callback, dispatch) => {
  let endpoint = 'localhost/api/index.php';
  let parameters = options.data;

  dispatch('SET_BUSY');

  Vue.http.post(endpoint, parameters, []).then((promise) => {
    return promise.text();
  }, (promise) => {
    return promise.text();
  }).then(response => {
    response = JSON.parse(response);

    dispatch('SET_NOT_BUSY');

    if (response.Result === 'ERROR') {
      console.log('ERROR: ' + response.Error.Message);
    }

    callback(response);
  });
};

动作函数需要 store 实例作为第一个参数。这通常由 Vuex 自动完成。

在Vue实例中使用action时,在Vuex 1中的实现方式如下:

import { setAppMode } from './actions'

new Vue({
  vuex: {
    actions: {
      setAppMode
    }
  }
})

现在您可以使用 this.setAppMode() 并让商店作为第一个参数自动可用。

注意:您还需要设置VM的store属性

import store from `./store`

// and inside the VM options:
{ 
    store: store
}

如果store还没有设置到vm实例,你仍然可以将它作为参数手动传递:

this.setAppMode(store);