Exploring the Limits with VUE Trailing Path Queries

My goal is to implement an optional query language functionality. When a user visits localhost/#/, the page should automatically redirect to localhost/#/?lang=en (defaulting to English).

If the user navigates to /localhost/#/?lang=es, the site will display in Spanish. Subsequently, any further navigation will maintain the chosen language by appending ?lang=es to all page paths.

This is the current code I have in place, but it is not functioning as expected:

Router:


router.beforeEach((to, from, next) => {
  let lang = from.query.lang;

  // Set language
  i18n.locale = lang || 'en';

  // Redirect with language query
  if(!lang){
    lang = 'en';
    console.log('Trying to push path: '+to.path+'/?lang='+lang)

    next({ path: `${to.path}/?lang=${lang}` });
    return; 
  }

The result is:

Trying to push path: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////?lang=en vue-router.esm.js?8c4f:1905 RangeError: Maximum call stack size exceeded

Answer №1

When it comes to redirecting to a different route within a router guard, remember to utilize next() with the updated parameters.

For more information, please refer to https://router.vuejs.org/guide/advanced/navigation-guards.html#global-guards

Here's a specific example:

Using next('/') or next({ path: '/' }) will redirect to a new location, terminating the current navigation and initiating a new one. The next function can accept a location object with various options like replace: true, name: 'home', or any parameter found in router-link's to prop or router.push

To put it into code:

router.beforeEach((to, from, next) => {
  let lang = from.query.lang;
  //Change language
  i18n.locale = lang || 'en';

  //Implementing the redirection
  if(!lang){
    console.log('Attempting to navigate to: '+to.path+'/?lang='+lang)
    next({ path: `${to.path}/?lang=${lang}` });
    return; // ensure that the code below does not run
  }

I hope this explanation is beneficial.

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

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

Typescript throws an error when Redux useSelector fails to properly infer the state

Seeking guidance on how to access my state using the useSelector hook import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { reducers } from './reducers'; export c ...

I'm currently troubleshooting the code for the Gallery project. The gallery is supposed to have 4x4 grids, but for some reason, the grids are

It seems like I am struggling to identify the exact issue. The display on mobile looks fine but not on desktop. I attempted to tweak the isotope configuration without success. Even manipulating the server-side code didn't reveal any obvious problems. ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

The reset function in Angular's template-driven form does not seem to be functioning properly when implemented using a component

Form Template Example <form #contactFormTemplate = "ngForm" (ngSubmit)="submitContactForm()"> <input type="text" class="form-control" name="name" [(ngModel)]="formData.name" ...

Where should we place the JavaScript reference in our CSHTML file in an MVC framework?

At the beginning of our .cshtml page in our current web application, we have included the following: @using Carwale.UI.PresentationLogic; @model Carwale.Entity.ViewModels.HomeModel @{ ViewBag.CustomJS = "~/Views/StaticPartials/HomeScripts.cshtml"; ...

Dealing with mouseover and mouseout events for ul li elements in Angular 9: An easy guide

Having trouble showing and hiding the span tag using mouseover and mouseout events. The ul and li elements are generating dynamically, so I attempted to toggle the display between block and none but it is not working as expected. Does anyone have a solutio ...

"Designing with Vue.js for a seamless and adaptive user experience

I'm looking to customize the display of my data in Vuejs by arranging each property vertically. Instead of appearing on the same line, I want every item in conversationHistory to be displayed vertically. How can I achieve this in Vuejs? Can anyone off ...

"Track the upload progress of your file with a visual progress

I have written this code for uploading files using Ajax and PHP, and I am looking to incorporate a progress bar to indicate the percentage of the upload. Here is the code snippet: <script> $("form#data").submit(function(){ var formData = new ...

Struggling to access subroutes of a Vue app without any success

Having some issues with accessing subroutes of my Vue app directly in production when hosted on Heroku. While I can navigate to www.example.com and access subroutes from the index page, typing www.example.com/subpage directly results in errors. For additi ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

What is the best way to eliminate an object from an array of objects that fulfills a specific condition?

Upon receiving an object in my function containing the information below: { "name": "Grand modèle", "description": "Par 10", "price": 0, "functional_id": "grand_modele_par_10", "quantity": 2, "amount": 0 } I must scan the next array of objec ...

Express: simplifying the use of middleware for app implementation

I am looking to update the code in my index.js file app.use(require('sass-middleware').middleware({ src: path.resolve(__dirname, '../'), dest: path.resolve(__dirname, '../public') })); app.use(require('browserify-dev ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

How to efficiently assign a random set of values to a group of players in Javascript/nodejs while ensuring each player does not receive their own inputted value

Within my array, I have stored the following information: players[{nickname: data.player, id: socket.id, data: playerdata}] The playerdata itself is an array playerdata[] In the first value of playerdata, each player has entered a string. (playerindex ...

When using VueJs, the input value may not clear upon pressing the ESC key for the first time

When I press the ESC key, my input should clear. However, I am experiencing a bug where the input is not cleared after the first press of the ESC key; it only clears after the second press. Even though the console displays an empty value for the input aft ...

react-router version 2.0 fails to direct traffic

I'm facing an issue with a piece of code that I have modified from the react-router project page. Despite my modifications, it doesn't seem to work as expected. Configuration In my setup, I have created several simple react components: var Ind ...

What is Mozilla's reasoning for deeming Conditional catch-blocks as non-conventional?

I recently came across a document on Mozilla that described the try...catch conditional as "non-standard and is not on a standards track. Do not use it in production" However, I am curious to understand the reason behind this statement. I also want t ...