1

我有一个可重用的 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
};
4

2 回答 2

1

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

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
};
于 2018-10-18T20:14:09.707 回答
0

这将起作用。

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

官方文档链接:accessing-global-assets-in-namespaced-modules

于 2018-10-05T13:53:45.200 回答