hi
im a backend developer , recently i've started working with vue for creating some small fullstack apps
one thing that i found very annoying was loading the resources/entities from backend and passing them to the components via props or directly in the component
so my idea was to register each component and its needed resources in a single class (resourceManager) , let the resource manager call the backend api and add the resources to the components after they are available
this way my components will be much cleaner , there wont be any duplicate backend calls and i dont have to worry about components loading at any point of app lifecycle
here is a simple example , i have 2 components Users.vue and Tasks.vue and they both need the users list from backend (please ignore any typo or syntax errors )
Users.vue
export default {
data() {
return {
users: [],
someLocalvar : false
}
},
created() {
this.resourceManager.registerComponent(this, [
{resource: 'users', route: {name: 'api.users'}},
])
}
}
Tasks.vue
export default {
data() {
return {
users: [],
tasks: [],
}
},
created() {
this.resourceManager.registerComponent(this, [
{resource: 'users', route: {name: 'api.users'}},
{resource: 'tasks', route: {name: 'api.tasks'}},
])
}
}
here is a simplified version of my resourceManager.js
class resourceManager {
constructor () {
this.resources = {}
this.components = {};
}
registerComponent(component, resources ){
let component_key = component.$options.__file?.split('resources/') [1]|| component.$.uid;
this.components[component_key] = {component , resources} ;
resources.forEach((item) => this.callApi(item.route) )
this.seedMountedComponent(component)
}
async callApi(route ){
if( this.resources[route])
{
// already called by another component , resource is in queue or available
return ;
}
// cll api and get the data && and to this.resources
this.resources[route] = axioscall(route).data;
this.resourceIsAvilable(route);
}
resourceIsAvilable(availableResourceRoute){
// loop this.components and add the available resource to them if they have it
for (const componentName in this.components) {
this.components[componentName].resources.forEach( (componentResource) => {
if(availableResourceRoute=== componentResource.route.name )
{
this.components[componentName].component[componentResource.resource] = this.resources[availableResourceRoute]
}
})
}
}
seedMountedComponent(component){
// loop available resources and add them to created component
}
}
this has made my work so much easier and cleaner , but not being a front developer im not sure if there a is problem with this approach that i dont see or maybe there is already a simple out of the box solution that does that
ofcourse there is more to do like if one component makes some changes to backend data it t should be updated in the resourcemanger and added again to the components ... i will handle those scenarios as well
i appreciate any feed back from someone with frontend experience