从服务文件分派变化

Dispatch mutations from service file

本文关键字:变化 分派 文件 服务      更新时间:2023-09-26

我有一个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);
  });
};

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

当在Vue实例中使用一个动作时,在Vuex 1中完成它的方法如下:

import { setAppMode } from './actions'
new Vue({
  vuex: {
    actions: {
      setAppMode
    }
  }
})

现在您可以使用this.setAppMode()并将存储自动用作第一个参数。

注意:还需要设置虚拟机的store属性

import store from `./store`
// and inside the VM options:
{ 
    store: store
}

如果store没有设置为虚拟机实例,您仍然可以将其作为参数手动传递:

this.setAppMode(store);