Changing the i18n locale in the URL and navigating through nested routes

Seeking assistance to navigate through the complexities of Vue Router configurations! I've dedicated several days to integrating various resources, but have yet to achieve successful internalization implementation with URL routes in my unique setup.

Here's the rundown: My project features nested router-views structured as follows:

.
├── /step
│   ├── /1 
│   ├── /2 
│   └── /3 
├── /join
└── /success

Here's a summary of my current progress:

  1. Upon app initialization, the default locale should display in the URL --> www.app.com/de and automatically redirect to /step. This logic is implemented in router index.js:
{
        path: '/',
        beforeEnter(to, from, next) {
          next(i18n.locale + '/step')
        }
      },

and in i18n.js:

//global variable to check language support
export const supportedLangs = ["de", "en"];

// check what url user has arrived at, retrieves "en", "de" etc
let langParam = window.location.pathname.slice(1,3)

export default new VueI18n({
  locale: supportedLangs.includes(langParam) ? langParam  : 'de',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages(),
})
  1. Retrieve language parameter from the URL (links may direct users to my app with specific /de or /en parameters). This functionality is set up in router index.js:
{
    path: '/:lang', 
    component: App,
    beforeEnter(to, from, next) {
      let lang = to.params.lang
      if ( supportedLangs.includes(lang) ) {
        if (i18n.locale !== lang) {
          i18n.locale = lang
        }
        return next()
      }
      return next(i18n.locale)
    }
}

I am encountering two issues that require assistance.

PROBLEM 1: Un-nested routes fail to render (e.g., www.app.com/de/join)

PROBLEM 2: Elements outside of App.vue content get duplicated, indicating incorrect route nesting (double app bar)

I have created a simplified code playground for reference -> HERE

Fingers crossed that someone can pinpoint where I might have gone astray!

Answer №1

After spending countless hours testing, I finally stumbled upon a solution that adheres to the correct structure. The missing piece was an empty component with <router-view /> for my dynamic language route.


const routes = [
  {
    path: "/",
    beforeEnter(to, from, next) {
      next(i18n.locale + "/step");
    },
    component: App
  },

  {
    path: "/:lang",
    component: { template: "<router-view />" },
    beforeEnter(to, from, next) {
      let lang = to.params.lang;
      if (supportedLangs.includes(lang)) {
        if (i18n.locale !== lang) {
          i18n.locale = lang;
        }
        return next();
      }
      return next(i18n.locale);
    },
    children: [
      {
        path: "step",
        redirect: "step/1",
        name: "Start",
        component: Steps,
        children: [
          {
            path: "1",
            name: "step1",
            component: Step1
          },
          {
            path: "2",
            name: "step2",
            component: Step2
          },
          {
            path: "3",
            name: "step3",
            component: Step3
          }
        ]
      },
      {
        path: "join",
        name: "join",
        component: Join
      },
      {
        path: "success",
        name: "success",
        component: Success
      }
    ]
  }
];

Here is the codesandbox link to the functional version. It's not clear why it's necessary, but it works perfectly for my project for now without questioning the mysteries of the universe :P

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

Bringing together Events and Promises in JS/Node is the key to seamless programming

I am exploring the most effective approach to incorporating events (such as Node's EventEmitter) and promises within a single system. The concept of decoupled components communicating loosely through a central event hub intrigues me. When one componen ...

Using PHP, jQuery, and HTML to submit a form and insert data into MySQL, all while

I am facing an issue with my PHP intranet site, which includes an HTML form with 2 input fields. My goal is to take the user's input from the form and insert it into a MySQL database without redirecting the user to another page. I have a separate PHP ...

Retrieve the content following a successful loading of the remote URL

I have been utilizing this function to retrieve content from a Remote URL function fetchContent($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $scrapedPage = curl_exec($ch); curl_close($ch); $content = $scrapedPage; return ...

What is the best method for executing computations within Vue.js 2?

Here is my second vue component: <template> <div class="row"> <div v-for="item in options"> <div class="panel panel-default panel-product"> .... </div> </div> ...

Unable to integrate Express.js into my React JS project

Having trouble integrating express.js into my react js Project. After adding the following lines to my app.js code: const express = require('express') const app = express(); I encounter the error messages below: - Module not found: Error: Can&ap ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Using Selenium to determine the quantity of elements that have a similar class present

Here is the test code I am using: it('count elements by class', async t => { let count = await driver.findElements(By.css('my-questions-class')).then(v => v.length); assert.equal(count, 3); // The count should b ...

Ways to resolve Error: Project needs yarn, but it is not currently installed

Just finished setting up my new project using the following commands: npm install --global yarn vue create elecprog yarn serve (-> encountered an error) Running everything through VS Code terminal. PS D:\elcp\elecprog> yarn serve yarn run ...

Tips for accessing the most recent embedded document added using the push() method

I'm having difficulty determining the feasibility of this situation. While using the mongoose blog example to illustrate, my specific use case is a bit more complex: var Comments = new Schema({ title : String , body : String , date ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Having trouble importing a module or library in VueJS?

After setting up a slider library called Hooper in VueJS 3, I imported it locally like this: <template> <hooper> <slide>1</slide> <slide>1</slide> <slide>1</slide> <slide>1</slide&g ...

Ways to automatically include a local variable in all functions

In each of my functions, I start with this specific line: var local = {} By doing so, it allows me to organize my variables using the following structure: local.x = 1 local.y = 2 Is there a way to modify all function prototypes to automatically include ...

After switching from jQuery to pure JavaScript, the code is now up and

After initially coding in jQuery + AJAX, I attempted to rewrite it in vanilla JavaScript. However, the code is not functioning as expected now. Can someone help me identify the mistake causing nothing to display when I run it through the server? I have che ...

Transform the Hue or Color of a PNG using ASP.Net, VB.Net, and jQuery

I am currently developing a web page that can combine multiple PNG images into one flat image for users to download. I am looking to incorporate a feature that allows for hue or color adjustments, similar to the color balance functionality in Photoshop. ...

What is the best way to declare a variable within a VueJS v-if condition without it being visible?

In my code, I have a specific template that is displayed when a certain condition is met using a v-if statement. In this template, I need to set a variable to N/A, but I am struggling with how to accomplish this simple task. <span v-if="se ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elem ...

What is the most efficient method for referencing nested descendants with ref in Vue? (Ancestor - Parent - Child)

Due to the unique project structure that cannot be changed, I am faced with the need to retrieve a value from a grandfather component all the way down to the grandson (Grandfather to Son's son relationship). The following code snippet illustrates this ...