The Language Switcher is not displaying the new language setting

Starting a fresh website using Nuxt, I am currently in the process of setting it up for multilingual functionality in French and English.

For setting up translation and language switcher, I referred to this specific tutorial and implemented the following:

Relevant segment of nuxt.config.js:

    ['nuxt-i18n', {
      detectBrowserLanguage: {
        useCookie: true,
        alwaysRedirect: true
      },
      strategy: 'prefix_except_default',
      defaultLocale: 'fr',
      parsePages: false,
      seo: true,
      pages: {
        about: {
          en: '/about-us',
          fr: '/a-propos'
        },
        portfolio: {
          en: '/projects',
          fr: '/portfolio'
        }
      },
      locales: [
        {
          code: 'en',
          iso: 'en-US',
          name: 'English',
          file: 'en-US.js'
        },
        {
          code: 'fr',
          iso: 'fr-FR',
          name: 'Français',
          file: 'fr-FR.js'
        }
      ],
      lazy: true,
      langDir: 'lang/'
    }]

navbar.vue

  <nav class="header">
    <div class="logo">
      <nuxt-link :to="localePath('index')">
        <img src="https://bulma.io/images/bulma-logo.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28">
      </nuxt-link>
    </div>
    <div class="links">
      <nuxt-link :to="localePath('about')">
        {{ $t('navbar.about') }}
      </nuxt-link>
      <nuxt-link :to="localePath('blog')">
        Blog
      </nuxt-link>
      <nuxt-link :to="localePath('portfolio')">
        Portfolio
      </nuxt-link>
      <nuxt-link :to="localePath('contact')">
        Contact
      </nuxt-link>
      <span>|</span>
      <nuxt-link v-if="$i18n.locale === 'fr'" :to="switchLocalePath('en')">
        English
      </nuxt-link>
      <nuxt-link v-else :to="switchLocalePath('fr')">
        Français
      </nuxt-link>

      {{ $i18n.locale }}
    </div>
  </nav>

Provided below is my directory structure:

layouts/
  front.vue
  navbar.vue

pages/
  index.vue
  about.vue
  blog.vue
  portfolio.vue
  contact.vue

The navbar.vue file is included within front.vue, which serves as the primary layout.

The encountered issues are as follows:

  • Upon clicking the languageSwitcher link on any page, it redirects to its English version (i.e.: /a-propos becomes /en/about-us), whereas the other links revert back to the French version.
  • {{ $i18n.locale }} consistently displays fr
  • Despite attempting the code block below:
<template>
  ...
  <nuxt-link
    v-for="locale in availableLocales"
    key="locale.code"
    :to="switchLocalePath(locale.code)"
  >
    {{ locale.name }}
  </nuxt-link>
  ...
</template

<script>
export default {
  computed: {
    availableLocales () {
      return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale)
    }
  }
}
</script>

It only shows English, whereas it should display both English and French.

What might I have missed or done incorrectly?

Answer №1

This solution worked well for me by utilizing vue-select along with the availableLocales feature from Nuxt-$i18n. I hope it proves helpful to you:

<template>
  <div>
    <client-only>
     <b-navbar>
       <div class="container">
      <b-navbar-brand
        class="navbar-brand-custom mr-2"
        :to="localePath('index')"
        :title="title">

      <div class="d-flex flex-row order-2 order-lg-3 ml-auto text-capitalize">
        <b-navbar-nav class="d-flex flex-row">
          <!-- Language menu -->
          <v-select
            v-model="selected"
            v-for="(lang, index) in availableLocales"
            :key="index"
            :value="lang.code"
            :searchable="false"
            @input="onChange"
            class="vue-select-custom"
          ></v-select> 
          <!-- Navbar menu -->
          <b-nav-item-dropdown
            id="menu-links"
            right
            no-caret
            role="manu"
            class="ml-0"
            menu-class="animated fadeIn text-right menu-links rounded-0"
          >
            <span class="dropdown-menu-arrow"></span>

            <template
              v-slot:button-content
              style="height:42px"
            >
          </b-nav-item-dropdown>
        </b-navbar-nav>
      </div>
    </div>
  </b-navbar>
  </client-only>

<script>
  export default {
   data() {
     return {
       selected: this.$i18n.locale
     }
   },
   computed: {
    availableLocales() {
     return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale);
   },
 },
 .....
 methods: {
  onChange(locale) {
    var language = locale.toLocaleLowerCase();
    this.$i18n.setLocaleCookie(language)
    this.$router.replace(this.switchLocalePath(language));
  },
  ....
 }
}

Answer №2

the reason for this behavior is the parameter alwaysRedirect: true, change it to false

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

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Maintain fullcalendar event filtering across multiple renderings

I currently have a fullcalendar that initially displays all events. I am using a select dropdown to filter the events, which works well. However, when the calendar re-renders after moving to the next month, it shows all events again. Here is my calendar in ...

Safari is encountering a 'Invalid Date' error in Javascript

Help me solve this issue with my script: var date = new Date("19871104071535".replace( /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/, '$4:$5:$6 $2/$3/$1' )); alert(date); The script run ...

Accessing the ID of individually selected rows as well as multiple rows in Vuetify data tables by utilizing the "show select" property

In order to delete specific records from the tables based on user selection, there needs to be functionality implemented where if a user selects any 3 options, a delete button will appear. This delete button should allow for the deletion of those specifi ...

The error message "MongoDB encountered an issue with accessing the property 'push', as it was undefined."

Exploring node.js, express and MongoDB is a learning journey for me. While working on data association in MongoDB models, I encountered a runtime error. Even though the reference has been added to the model, the push() method fails to recognize it. Here ar ...

Guide on implementing a filter on an image using P5 in a React application

Seeking clarity on a specific issue, I'm using a react-P5-wrapper to create my P5 canvas in React, and I want to apply a filter to an image. Typically, in P5, this would be done with image.filter(GRAY). However, when P5 is an instance in React, I can& ...

Creating a hexagonal grid pattern with the use of texture

I have conducted several experiments in the past to determine the most effective way to create large-scale hexagon grids. I attempted drawing the hexagons using THREE.Line and THREE.LineSegments. While this method was successful for small grids, the perfo ...

problem with creating a django template script

Hello, I am currently working on a code that is responsible for executing various functions within the template. I have utilized scripts to verify these functions using if-else statements and for loops. However, I am encountering some errors during this pr ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

Updating Jqplot display upon ajax call completion

Currently, I have a Jqplot set up using the AJAX JSON Data Renderer and it's functioning properly. There is a button on the page where users can input new values (updated through ajax) which are then stored in the same DB as the json data source. Whe ...

Automatically refresh the D3 Sunburst visualization when the source json is modified (items added or removed)

I'm a beginner in D3 and I'm attempting to update the chart dynamically if the source JSON is modified. However, I'm facing difficulties in achieving this. Feel free to check out this plunkr Js: var width = 500, height = 500, radi ...

Having trouble getting the onClick event to trigger in React?

I have a button in my navbar that triggers a submenu (list of items) to display when clicked. Each item is a separate child component and I want them to trigger an event when clicked. However, the onClick event listener does not seem to be working. Other m ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

Translating Encryption from Javascript to Ruby

I have an application which utilizes HTML5 caching to enable offline functionality. When the app is offline, information is stored using JavaScript in localStorage and then transmitted to the server once online connectivity is restored. I am interested in ...

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Issues with managing multiple user sessions in express-session

I've been struggling with an issue for a few days now and haven't been able to find a solution. I've scoured forums and documentation, but nothing seems to work. I have a website built in Node.js, using express-session and passport for sessi ...

Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below: { "results" : [ { "address_components" : [ { "long_name" : "286", "short_name" : "286", "t ...

Addressing some minor visual inconsistencies in an HTML bullet-pointed list

After reviewing my current code, it is displaying the following: https://i.stack.imgur.com/dvjrc.jpg I am attempting to make the following changes: Ensuring each line in the list fits properly within its corresponding box by utilizing vertical-align: to ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Why am I not receiving any results from the communication between JavaScript and PHP using an HTTP GET request?

Currently, I have a small JavaScript program running within an HTML5 canvas and included a HTTP GET request function in my JavaScript code. The function itself is functioning properly as I tested it with multiple examples from the internet, all of which wo ...