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

Tips on mapping API response to the data attribute in Nuxt framework

I am currently in the process of modifying a section within a form. In this section, I will retrieve data using the content's id from an API. My goal is to map the returned data into an array in the data property so that it can be easily patched. Bel ...

trouble seeing images with an array input and ngFor in Angular

I am encountering issues while attempting to exhibit an array of images by their source link using ngFor. It seems like there are errors hindering the functionality! Below is the image HTML code located within my card component: <div class="Session-Pa ...

Adding complex JSON format to an HTML table involves formatting the data correctly and then using

Utilizing AJAX, I fetched a JSON response and am now looking to map the JSON data into an HTML table structured like this: { "records": [{ "type_id": 000001, "type_desc": "AAAAAA", "type_createby": "Adam" }, { "type ...

Creating dynamic navbar links in Vue.jsIn this guide, we will explore how to give the active

My goal is to assign a different color to each menu item when it's active. I've tried to achieve this by following these two code examples: 1 -> https://codepen.io/Ranushka/pen/KKPBYQv 2 -> https://codepen.io/Ranushka/pen/ZEzjdrO However ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

Encountering a Vueify Typescript error in a Vue project

Recently diving into the world of Vue, I was able to successfully create a sample app using gulp, vueify, and TypeScript. To showcase what's happening and shed light on an issue I'm facing, here are snippets of the key code segments: Menu.ts im ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

What is the best way to show only a specific v-for element in Vue.js?

Is there a way to select a specific item from a v-for loop in vue js? I am using v-for to retrieve Youtube data API items. Each item contains an iframe that should only be displayed when a user clicks on a play button. Currently, all the iframes are shown ...

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

Looking to divide a multiple-page .TIFF document into several PNG or JPG files using the sharp module in node.js?

Is there a way to split a single .tiff file with multiple pages into several .png or .jpg files without using ImageMagick or GraphicsMagick due to limitations in my codebase? I am unable to install CLI tools so I'm exploring alternate solutions. I kn ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

Dynamically generating Vue components

I have a component that displays all articles, and I want to add a 'Read more' button to each article so that users can open the full content by clicking on it. The article page should pull full information from an API and have its own route path ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Managing data binding for checkboxes within a constantly changing set of options

I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox. The input data that will be provided to the directive looks something like this: [ { ...

Can you explain the contrast between using require('d3') and require('d3-selection')?

While working on a nodejs application with javascript, I encountered an interesting issue. In my code, I am passing a d3 selection to a function as shown below. // mymodule.js exports.myfunc = function(ele){ if(ele instanceof d3.selection){ // do so ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

Navigating a plethora of unpredictable identifiers using AngularJS

My goal is to display content from a json file that varies in type and consists of pages divided into chapters. Users can navigate through the content using an aside menu or next and previous buttons. Currently, I am able to display the content by inserti ...

Unable to host Express app on Firebase functions emulator due to a port conflict with error code EADDRINUSE: address already in use :::3000

Testing the deployment of an express app on Firebase using Firebase functions has presented a challenge for me. Upon running the command firebase serve, I encountered the error EADDRINUSE: address already in use :::3000. Below is my index.js file: const fu ...