In my application, I have a component named Foo
, which serves as the template for a route called app/foo
. Within this component, there are child components that also act as templates for routes such as app/foo/bar
and app/foo/baz
.
I've implemented a binding of a global vuex
store object to the query
property of the route. This allows the URL params to dynamically change based on the object's values. For example, if the object is set to {a: 1, b: 2}
, the URL params will display as ?a=1&b=2
. If the user modifies the params to be ?a=0&b=0
, the object will update accordingly to {a: 0, b: 0}
. So far, this functionality works correctly.
However, the issue arises when navigating to any subpath under app/foo
; the route's query
property is lost, causing the URL params to disappear.
One way to address this is by passing the query
object dynamically using:
this.$router.push({ name: 'bar', query: this.$route.query });
Yet, this approach becomes challenging to maintain over time.
I'm aware that Vue Router offers additional life-cycle events, and I believed I could update the query within the beforeRouteUpdate
event of the Foo
component. After trying different methods, I encountered some obstacles:
beforeRouteUpdate (to, from, next) {
// Attempting to modify the query results in an error due to it being read-only
to.query = from.query;
// Updating the query in this manner does not achieve the desired effect
this.$router.replace({ query: from.query })
next();
},
Edit:
I also experimented with setting a watcher on $route
to replace the query upon route changes. However, this caused an infinite loop:
watch: {
$route(to, from) {
this.$router.replace({ query: from.query });
}
}
If anyone has insights on how to maintain the Vue Router query persistently at a component level, I would greatly appreciate your guidance.