Maintain Vue Router Query Parameters Across Parent Components

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.

Answer №1

After considering @craig_h's suggestion, I implemented a watcher on $route:

watch: {
  $route(to, from) {
    if (to.path != from.path) { // to avoid infinite loop
      this.$router.replace({ query: from.query })
    }
  }
}

While this solution covers most scenarios, there is an exception when a component accidentally navigates to the current route. In such cases, the query would still be lost due to identical values of to.path and from.path.

To tackle this issue, I decided to include additional checks in components that may lead to the current route:

if ((name != this.$route.name) || (params != this.$route.params)) {
  this.$router.push({ name, params });
}

This approach resolves the issue but is not without its drawbacks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

How can the first paragraph value of a div be found using jQuery in Next.js?

How can I retrieve the value of the first <p> tag within my div when a button inside the same div is clicked? Despite attempting to use $(this), it doesn't appear to be functioning as expected. Take a look at the code snippet below: <div cla ...

Issue with Vuexfire {serialize} option causing improper formatting of arrays

I am attempting to aggregate all the Firestore document Ids when querying a collection. While I can successfully query all collections within an instance, I am struggling to correlate their document Ids with the collection arrays. The following code allow ...

Tips for incorporating css styles and javascript into handlebar files

I've been trying to figure out how to add styles and js to my handlebar files, but I'm hitting a roadblock. I attempted to use partials to store the stylesheet tags and then include those partials in the handlebars file, but it didn't work a ...

Most effective method to change a specific attribute in every element within a nested array of objects

Below is an example of my data object structure: const courses = [ { degree: 'bsc', text: 'Some text', id: 'D001', }, { degree: 'beng', text: 'Some text&apos ...

Conceal component while navigating in VueJs

I am working on a Vue project. I am trying to implement a feature where a component is hidden while the user scrolls, but then reappears once the scrolling stops. I have tried using a scroll event, but the component does not show up again. <div c ...

Issue with Firefox causing problems with smooth scrolling Javascript on internal links

I recently created a one-page website using Bootstrap. The navigation menu items are internal links that point to different sections within the page, and I added some smooth scroll JavaScript for a more polished scrolling effect. While the website functio ...

Trigger another mutation when the checkbox is unchecked

<li v-for='item in resultQuery' :key='item.id'> <label class='custom-checkbox'> <input type='checkbox' :value='item' v-model='checkBrands'> <span @click='loadP ...

Implementing Tag Manager in Vue.js: A Step-by-Step Guide

I'm facing an issue with my vue.js project. I have a function that needs to be added to the head of my project. However, when I tried adding it to index.html, which is where the function (a tagManager creation) belongs, it didn't work properly. T ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

The functionality of React useState seems to be operational for one state, but not for the other

I am currently working on developing a wordle-style game using react. Within my main component, I have implemented a useEffect that executes once to handle initialization tasks and set up a "keydown" event listener. useEffect(() => { //The getWor ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

Using Cheerio with a Node.js bot

I am currently utilizing Cheerio to extract information from web pages in my .js files. However, I would like these files to automatically restart every 1 day to check for any new data. Instead of using setTimeout, which may not be efficient for managing ...

Error: The function styles$1.makeStyles is not defined

Currently, I am experimenting with rollup for bundling. However, when I run the code, I encounter the following problem: https://i.stack.imgur.com/8xLT3.png import { makeStyles } from '@material-ui/styles'; const styles = makeStyles({ subHead ...

Retrieving PokéAPI image information

My goal is to display images from the PokéAPI on my app's homescreen when it is opened. However, I am facing a challenge where I need to call 30 different APIs in order to show 30 images. Calling these APIs one after another every few seconds seems l ...

Arrange an array that has been sifted through

I'm having trouble figuring out where to place the .sort() method in the code snippet below. I've tried multiple placements but it either gives errors or doesn't work as intended. My goal is to sort the list alphabetically in this scenario. ...

Displaying exclusively distinct values in the selection box/dropdown menu

My goal is to retrieve data from the SQL server database and populate the corresponding fields on the frontend. While I am able to fetch the data, some fields in the response contain duplicate values in the dropdown menu. Here is an example of how my Compo ...

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

Overcome the issue of 'Parsing Error: Kindly verify your selector. (line XX)' in Javascript/AWQL

Hello there! Just to clarify, I am not a developer and my coding skills are limited to basic HTML. Your patience is greatly appreciated ...

Having trouble displaying form in a different view, form is not appearing as expected

I am facing an issue with rendering a form inside a modal. The form is being rendered but the form_for does not show up, only the inputs are visible. This prevents me from targeting the submit button, which I need for ajax functionality. My file path: Adg ...