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

What is the best way to conditionally render one of several components in a manner that is compatible with React's change detector?

Within my CRUD application, I have incorporated various reusable components such as a "generic" DialogComponent, along with several non-reusable components. Throughout the development process, I have encountered numerous instances where I need to either: ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Generating directives on the fly

I am relatively new to AngularJS and have a good understanding of the basics. My goal is to create a desktop interface where items are loaded dynamically from a database using $http. I have already developed a directive that displays a title and an icon fo ...

Exploring the world of AngularJS and delving into the

Lately, I've come across articles discussing Google's ability to now crawl websites and render CSS and Javascript. For example, Google themselves have talked about it in this article: My setup involves a single page application built with Angula ...

Strategies for managing Shopify's API request restrictions with the microapps Node.js module

I've been struggling to find a solution to this problem and I just can't seem to get it right. I'm currently using a Node.js module for the Shopify API created by microapps. In my JSON object, I have a list of product IDs and SKUs that need ...

Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API: [{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}] Using Ajax: $.ajax({ url: 'interface_API.php', ...

What is the best way to manage zoom settings following a completed search query?

Whenever I try to search for an address using this map, it zooms in way too much making the map unusable. Despite my efforts to adjust the map bounds, I have not been successful. It seems like I am on the right track but for some reason, it just isn't ...

Sorry, there was an error with Vue-i18n: Unable to access the 'config' property because it is undefined

Let's start by examining what functions correctly in App.js import router from './routes.js'; import VueI18n from 'vue-i18n'; const messages = { en: { message: { hello: 'hello world' } } } // Create ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Having trouble receiving a JSON array after making an Ajax request

I have read through previous posts on this issue, but I still can't seem to figure it out. Hopefully, someone here can help me solve this problem. My challenge lies in retrieving an array, which I have encoded in json, from a PHP script and passing i ...

Issues with Alignment of Items in Vuetify Data Table Columns

Upon reviewing the code provided, it appears that while the column headers and pagination display correctly (2 pages with 5 records each), all the data is showing in the first column in a jumbled manner. <!DOCTYPE html> <html> <head> ...

Issue with Vue Apollo 4 fetchin wrong data from GraphQL API

We are currently facing an issue while trying to utilize version 4 of Vue apollo along with the composition API following the steps outlined in this particular tutorial. Despite our efforts, we are unable to retrieve any results from a standard graphql que ...

Unable to retrieve HTML content through a Node.js server

I created a HTML webpage that includes .css, images and JavaScript files. However, when I start my node server using the command below: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); The webp ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Updating visual appearance with button clicks and unclicks

Is there a way to dynamically update the button image while clicking on it? This is what I have tried: $('.gamebox_minimap_plus').click(function() { $(this).css("background-image","url('gfx/plus2.png')"); }); The image ch ...

Is it possible to hide the <dd> elements within a <dl> using knockout's custom data binding upon initialization?

I have implemented a <dl> where the <dd> can be expanded/collapsed by clicking on the corresponding <dt> using knockout's data binding. The inspiration for my solution came from a tutorial on creating custom bindings. Currently, I h ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

What is the best way to design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...

Using Vuex to iterate through an array of objects and implement a conditional statement based on a specific key-value

In my VueX implementation, I am fetching data and then iterating through an array of objects to extract the menu_code. The objective is to display or hide a button based on the following conditions: Show the button if at least one item in the menu_code ar ...