Reputation: 258
I'm currently using Vue Router's beforeEnter
hooks to retrieve data for one of my routes.
{
path: '/A',
beforeEnter: (to, from, next) => {
loadData();
next();
},
}
A simple example of the flow would be:
Navigate to Route A --> Loading Data
Navigate to Route B
Navigate to Route A --> Loading Data again
How can i prevent the second & obsolete API Call? since it's not important that the data is that up-to-date.
I could do: if (!dataIsAlreadyThere) loadData()
, but this is somehow not nice to have with many routes. Are there any other solutions or ideas out there?
Upvotes: 2
Views: 2424
Reputation: 8435
The following should work according to some clues from the vue and vue-router documentations:
Wrap your router-view inside a keep-alive element
Fetch the API inside the mounted hook of your component:
mounted () { this.data = loadData() }
In theory, this should only mount the component once and keep its state alive, even when the router is switching components inside the router-view.
Note that this is not the preferred way which vuejs or the vue-router itself suggest. Vue suggest using external state management like vuex.
Upvotes: 2