When navigating into the same route you are currently at, the route query page added by the before enter route guard is lost.
This is due to the fact that router link to object does not contain query page, and it does not go into before enter hook anymore, since it is already in the same route.
I figured out that you can add it in your router push or link button and you need to add this whenever you know the view contain query page.
Example:
this.$router.push({ name: 'routeName', query: { page: 1 } });
Question:
Is there an elegant way to handle this in route guard?
Which hook should I use so that route query page can be kept even user navigate into the same route?
Example code:
Route
// Sample route
const routes = [
{
path: 'test',
name: 'Test',
component: TestPage,
beforeEnter: testPageGuard,
},
];
Route Guard
// Test Page Guard
testPageGuard: (to, from, next) => {
const { page = null } = to.query;
let finalNext;
if (!page) {
finalNext = {
...to,
query: {
...to.query,
page: 1,
},
};
}
if (finalNext) {
next(finalNext);
} else {
next();
}
}
View
// TestPage.vue
<template>
<!-- The problem can be reproduce when clicking this link
when you are already in route '/test' -->
<router-link :to="{ name: 'Test'}">
Test
</router-link>
</template>
<script>
export default {
name: 'Test',
};
</script>
Solution Figured:
- Add query page to router link
// TestPage.vue
<template>
<!-- query page is added here -->
<router-link :to="{ name: 'Test', query: { page: 1 } }">
Test
</router-link>
</template>
<script>...</script>