1👍
✅
You’re on the right path. Your error might come from query conflicts. You could try validating the query params from both directions first and then pass them along:
// guards.js
export const persistRouteQuery = (to, from, next) => {
const query = { ...to.query, ...from.query }
if (!Object.keys(to.query).length && Object.keys(from.query).length) {
next({ ...to, query })
} else {
next()
}
}
// router.js
router.beforeEach(persistRouteQuery)
Heres a more robust solution based on the previous code and your example that passes along only explicitly defined route queries:
// guards.js
const persistentQueries = ['displayNav']
const hasQuery = (route, queryKeys = [])=> {
const keys = Object.keys(route.query)
const hasKeys = !!keys.length
if (queryKeys.length && hasKeys) {
return keys.some((k) => queryKeys.includes(k))
}
return hasKeys
}
const toWithQuery = (to, path, queryKeys) => {
const query = to.query
const params = to.params
const withQuery = queryKeys.reduce((keys, key) => {
if (query[key]) {
keys[key] = query[key]
}
return keys
}, {})
return { path, params, query: withQuery }
}
export const persistRouteQuery = (to, from, next) => {
if (!hasQuery(to) && hasQuery(from, persistentQueries)) {
next(toWithQuery({ ...to, query: from.query }, to.path, persistentQueries))
} else {
next()
}
}
// router.js
router.beforeEach(persistRouteQuery)
There is also another thread about passing query params to child routes that might help you.
Source:stackexchange.com