Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter.

Instead of manually modifying each router-link and router.push, I am looking for a solution using router.beforeEach method.

Although I attempted the following code snippet, it resulted in an infinite loop:

router.beforeEach((to, from, next) => {
  if (from.query.userId) {
    next({
      path: to.path,
      query: Object.assign({}, to.query, from.query.userId),
    })
  }
  next()
})

Is there a way in vue-router that allows me to maintain a query parameter from a previous route if it exists?

Answer №1

I encountered a similar issue and managed to come up with a working solution for production:

router.beforeEach((to, from, next) => {
    let requiresAuth = (to.meta.hasOwnProperty('requiresAuth') ? to.meta.requiresAuth : true);

    //... explanation
    if (!store.getters.isAuthenticated() && requiresAuth) {
        next({name: 'login', params: {...{redirect: to.name}, ...to.params}});
        return;
    } else if (store.getters.isAuthenticated() && !store.getters.isDataPreloaded() && to.name !== 'preloading') {
        //... explanation
        next({name: 'preloading', params: {...{redirect: to.name}, ...to.params}});
        return;
    }

    next();
})

Whether you choose to utilize query or params is up to you. Optionally, you can include parameters to indicate certain actions during redirection. By adding an optional param like redirected, you can differentiate between actions in your beforeEach method.

Keep in mind that the params property allows exchanging data between routes without revealing it in URLs to users.

Here's a breakdown of why and how my code functions:

  1. User accesses page
    example.com/my-private-zone/dashboard/reports
  2. System checks authentication status; if not authenticated, saves current route as from and redirects to login page example.com/login.
  3. User successfully authenticates
  4. User gets redirected to preloading page (example.com/preloading) for JS script preloading.
  5. Finally, user returns to initial route from step 1, passing entry point as redirect param for seamless redirect without URL changes.

Your code should also work fine, but don't forget to include a return statement within your if branch:

router.beforeEach((to, from, next) => {
  if (from.query.userId) {
    next({
      path: to.path,
      query: Object.assign({}, to.query, from.query.userId),
    })
    return;
  }
  next()
})

I hope this clarification is helpful!

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

Should we pause JQUERY AJAX to prioritize usability, or only when absolutely necessary?

I am struggling with my LoadingStatus Function, which has two options: SHOW and HIDE. When a JQUERY POST is made, the Show option triggers to display, while the HIDE option occurs after the RESPONSE comes back. The problem I'm encountering is that s ...

The Webpack dev server encounters an issue serving wasm files with an incorrect mime type

I'm working with Vue 2 (although my question may not be specific to Vue). The application I'm developing utilizes a WebAssembly library that I installed using npm install [directory_name]. However, when I execute npm run serve, the server is serv ...

Improving the Efficiency of JavaScript/jQuery Code

Currently, I am delving into JavaScript and jQuery. Here is the code snippet that I am working on: $("#hrefBlur0").hover(function() { $("#imgBlur0").toggleClass("blur frame"); }); $("#hrefBlur1").hover(function() { $("#imgBlur1").toggleClass("blur fra ...

Creating HTML elements using Vue.js

Currently, I am facing an issue while attempting to render a template using the push mutation method. My goal is to push a section component, but instead of seeing the desired template content on my page, I am only getting the raw output of <vsection> ...

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

Node-archiver: A tool for dynamically compressing PDF files

I am currently working on a project that involves generating multiple PDF files using pdfkit. I have an array of users, and for each user, I create a report using the createTable() function. The function returns a Buffer, which is then passed to archiver t ...

A step-by-step guide on accessing grouped column data in Angular UI Grid

How do we access the data of all rows within a grouped column in Angular UI Grid? For instance, when looking at the Grouping Tutorial, how can we retrieve all the company names from the 'Company' column? I have successfully obtained the aggrega ...

Ways to develop tests for functions specific to my scenario

Currently, I am attempting to implement a timeout function test within my application. Within the controller: $scope.$watch('toy',function(toyVar){ if(toyVar == 1) { //perform actions } else { $timeout(f ...

When utilizing a Slick carousel with three slides and setting autoPlay to true, the slider-nav behaves as if there are five slides

I am currently using the Slick carousel plugin and I want to feature a display of 3 photos. The issue is that when I set slidesToShow=2, everything works perfectly fine, but when I try to set slidesToShow=3, which equals the total number of slides, the bot ...

Implement a unique navigation bar for each page using layout.js in Next.js

https://i.stack.imgur.com/Ha3yC.pngI have a unique setup in my next js project with two different navbar layouts and ten pages. I'm looking to assign navbar one to five pages and navbar two to the remaining pages using layout.js. Can anyone provide gu ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

Attempting to embed a script tag within an Inertia and Vue component

Can anyone help me with SSR rendering Schema data for my blog post using a Vue/Inertia component template? When I attempt to render the data, I encounter the following error: [plugin:vite:vue] Tags with side effect (<script> and <style>) are i ...

Is there a way for me to display a customized error message using antd components?

During the registration process using React and Antd, if the backend returns the error message "user already registered" after clicking on "Sign up", it should be displayed in the form. You can customize the display as shown below: An example of how the u ...

Utilizing data from an external JavaScript file in an Express application

I am currently developing an application using Node.js Express, where I need to pass some data from Express and utilize it in an external JavaScript file. Below is my app.js: const express=require('express'); const path=require('path&apos ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Having trouble with Autocomplete not entering cities into the form?

While experimenting with Google's API, I have encountered confusion regarding why cities like Staten Island, Brooklyn, Queens, and various others are not being placed into the form like other cities. According to Google's API, "locality" is suppo ...

Remove the image by clicking on the "X" icon located on the top right corner of the image

One of my tasks involves deleting an image by clicking on the "X" mark located at the top right corner of the image. To achieve this, I referred to this CSS fiddle http://jsfiddle.net/yHNEv/. Sample HTML code: <div class="img-wrap"> <span ng-c ...

Navigating nested objects in JSON from an API: A guide to accessing hidden data

I am currently utilizing the cryptocomare API to retrieve data on various crypto coins within a Nextjs App. My approach involves redirecting users to the coin details page when they click on a specific symbol. I then attempt to extract this clicked symbol ...

Persisting Undefined Values Even After Proper Prop Passing

I'm currently working on fetching and passing coaching data as props to another component for rendering on the frontend. I need to pass these props to the CoachingCard Component in order to display the coaching values. However, I'm encountering ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...