在加载时将数据传递给 Vuex 中的模块

Pass data to module in Vuex on load

我有一个可重用的 Vuex 模块,用于 API 的 CRUD 方法。如何在加载时从父模块传递相关的URL? 例如

company.module.js

var URL;
const state = {
   all: [],
   items: [],
   editing: false,
   url: URL
};
...
export default {
   state,
   getters,
   actions,
   mutations,
   modules: {
     crud: crudModule
   }
};

crud.module.js

const state = {
    url: '', // Get the URL from company.module here?
    status: {
        loading: false,
        success: false,
        error  : false
    }
};
...
const actions = {
     async fetchItems(context, data ) {
         commit('QUERY_REQUEST');
         var url = '';// Or get the URL from parent state?
         return axios.get( url )
             .then( response => {
                 ...
             });
     },
}
...
export default {
     namespaced: true,
     modules: {
         meta: metaModule
     },
     state: () => state,
     getters,
     mutations,
     actions
};

这将起作用。

 async fetchItems({commit, rootGetters }, data ) {
     commit('QUERY_REQUEST');
     let url = rootGetters['company/url']
 }

link转官方文档:accessing-global-assets-in-namespaced-modules

我明白了。我没有使用模块,而是将 crud 状态、getter、突变和操作放入 class 中,并将端点作为参数。然后我可以在我的每个命名空间模块中使用 Crud class 并使用展开运算符合并它。

crud.js

export default class {
    constructor ( endpoint ) {
       this.state = {
          url: endpoint,
          status: {
            loading: false,
            success: false,
            error  : false
          }
       };

        this.getters = getters;
        this.mutations = mutations;
        this.actions = actions;
    }
}

const getters = {
  //...
};
const actions = {
  //...
};
const mutations = {
  //...
};

company.module.js

import Crud from './api/crud';
let endpoint = "/api/companies";

var crud = new Crud( endpoint );

const state = {
    ...crud.state
};

const getters = {
    ...crud.getters  
};

const actions = {
    ...crud.actions
};

const mutations = {
    ...crud.mutations
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};