Is there a way to trigger a store action in Vue2 and vue router 3x whenever a specific child route is accessed, regardless of whether it is through a button click or the browser back/forward buttons?
I have the need to make an API call every time a particular child route is visited. While my current code functions properly when navigating through buttons, it breaks when users use the browser's navigation buttons.
Let me explain the issue...
The structure of my router is as follows:
const router = new Router({
mode: 'history',
routes: [
{
path: '/browse/food/:foodId',
name: 'Food',
component: foodComp,
children: [
{
path: ':routeTitle',
name: 'FoodDescription',
component: foodDescriptionComp,
props: {
viewMode: 'TEXT',
},
},
{
path: ':routeTitle',
name: 'FoodImage',
component: foodDescriptionComp,
props: {
viewMode: 'IMAGE',
},
},
{
path: ':routeTitle/food-translation',
name: 'FoodTranslation',
component: foodTranslationComp,
},
],
},
...lotsOfOtherRoutes,
],
});
...the foodDescriptionComp
includes pagination for switching between different foods triggered by clicking the "next page" (or page number) button. The method for this functionality is defined as follows:
methods: {
async switchPage(pageNumber, foodIdForPageSelection) {
this.$router.push({
name: 'FoodDescription',
params: { foodId: foodIdForPageSelection },
});
await this.loadFoodByPage({
catalogId: this.catalogId,
pageNumber,
});
}
}
When a user uses the browser's back button, the loadFoodByPage
method is not triggered. I've attempted several solutions:
One approach was to use the beforeEnter
function and move the loadFoodByPage
logic there, but it only fires on the initial page load.
Another potential solution could involve using beforeEach
, but with hundreds of routes in our application, it seems excessive to add logic specifically for one child route that would be checked on every single page.
Although I tried a workaround involving the following hacky solution, it results in maintaining only one step in the history when pressing the back button - meaning if I navigate from login to food 1, then proceed to 2, 3, 4, and press back in the browser, it will go back to page 3 before redirecting to the login page. Even if this method worked, it goes against best practices.
// Reload page on browser back/forward button press
window.onpopstate = function () {
window.location.reload();
};