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

时间:2018-09-13 04:44:04

标签: vuex vuex-modules

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

2 个答案:

答案 0 :(得分:1)

我知道了。我将模块的状态,获取器,变异和操作放入模块而不是模块中,并以端点作为参数。然后,我可以在每个命名空间模块中使用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
};

答案 1 :(得分:0)

这将起作用。

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

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