Reputation: 1
Consider the following Widget component.
<template>
<component :is="name" />
</template>
<script>
import { mapActions } from 'vuex';
export default {
props: {
name: {
type: String,
required: true
}
},
created() {
this.addWidget(this.name);
},
methods: {
...mapActions({
addWidget: 'widgets/add'
}) // adds widget name to an array
}
};
</script>
I want to have multiple components like this one all over the page. I need to be able to gather all of the component names so I can fetch the relevant data for them.
My current idea is to add the component name to the store when the created
hook fires.
That works just fine, but my problem is that I can't find a way to dispatch
a Vuex
action to fetch the data once all of the components have been created. I tried using various hooks to no avail since none of them seems to have Vuex
access.
Am I missing something? Is there some kind of hook that fires after all of the components have been created (SSR
) that has Vuex
access. Or maybe there's some better way to achieve what I've been trying to do?
Upvotes: 0
Views: 384
Reputation: 791
Why do you want to wait until all the widgets have been loaded to fetch the data? Instead, what I'd do is fetch the data for each Component as they get added in the page. Using this approach, each component would require a specific piece of data, and nothing better than to load each of them in a different request. Easier to test, easier to trace, adheres to the single responsibility principle.
If you are worried that two components may require the same data, then you can route all requests through an Object that hashes the request (endpoint + verb if using REST) and keeps a pool of active connections, so that if two requests come in one reuses the Promise of the other, and only one of them reaches the server.
Now, if you really want to do it using your original approach, make it so that each widget emits an event once it's been registered. The events are collected by the parent component (maybe the Page that loads all the widgets). The page knows which Widgets are being loaded. Every time an event is received it sets a flag on that specific widget to indicate it's been loaded. Once all widgets get a flag, the Page triggers a request to fetch the data.
Upvotes: 1