I have a reusable Vuex module for CRUD methods to an API. How can I pass the relevant URL from the parent module when loading? e.g.
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
};
I figured it out. Instead of a module, I put the crud state, getters, mutations and actions into a class with the endpoint as a parameter. I can then use the Crud
class in each of my namespaced modules and merge it using the spread operator.
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
};