Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale dynamically so that all translated fields display the correct language. When I update the locale in new VueI18n({}) definition and save the file, everything works as expected.

In my scenario, the language choices are displayed as items on a menu:


    <v-icon color="primary" dark slot="activator">
        person
    </v-icon>
    <v-list dark class="primary">
      <v-list-tile>
        <v-list-tile-title>{{ getUser.userId }}</v-list-tile-title>
      </v-list-tile>

      <v-divider />

      <v-list-tile @click="passDialog = !passDialog">
        <v-list-tile-title>Password</v-list-tile-title>
      </v-list-tile>
      <v-list-tile @click="logoutClick">
        <v-list-tile-title>Logout</v-list-tile-title>
      </v-list-tile>
      <v-list-tile>
        <v-list-tile-title @click="setLocale('en')">English</v-list-tile-title>
      </v-list-tile>
      <v-list-tile>
        <v-list-tile-title @click="setLocale('es')">Spanish</v-list-tile-title>
      </v-list-tile>
    </v-list>

and the click handler triggers a method passing the selected locale:


setLocale(locale) {
  this.$root.$i18n.locale = locale;
},

The VueI18n is initialized as follows:


import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default new VueI18n({
  locale: 'en',
  localeDir: 'locales',
  fallbackLocale: 'en',
  messages: loadLocaleMessages(),
});

I've tried different approaches like using this.$i18n.locale = locale; or i18n.locale = locale; after importing i18n from '@/i18n'; in the component. However, none of them seem to update all field names that have translations. It feels like a re-render of the translated values is needed once the language changes.

What am I missing to ensure all translated values update when changing languages?

UPDATE: Upon revisiting my setup based on feedback, I realized a crucial part I missed. Each field has multiple Vuetify attributes extracted to a separate fields.js file. Here's an example of field definitions:


...
userId: {
    label: i18n.t('users.generalInfo.userId'),
    ...
}
...

It's these fields that aren't updating with language changes. Binding the label directly in the component does update the label value accordingly:


<v-text-field 
  v-bind="fields.userId" 
  v-model="userModel.userId"
  :disabled="!canSave"
  :label="$t('users.generalInfo.userId')"
/>

Seems like the issue lies within the bound file, even though it includes i18n.js where the locale is set.

UPDATE 2: It appears others have faced similar challenges (view GitHub issue).

Answer №1

If you are referring to the usage of label: i18n.t(...), please note that it will only be executed once. Changing the language will not update the label accordingly. One workaround is to store the text keys in your fields and utilize $t in your component for the variable containing the text key:

field.js

...
const fields = {
  userId: {
    label: 'users.generalInfo.userId',
...

component

<v-text-field 
  :label="$t(fields.userId.label)"
/>

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

Managing the display of an extensive list of items in react - best practices

I'm facing a challenge with performance as I have a significant number of items to render and the data is constantly being updated in real-time via socket-io. How can I optimize for performance when the table of items is being rendered frequently due ...

Is there a way to access a PHP value within a self-invoked jQuery function?

I have a page that creates n links using a foreach loop: ...some html and php code <?php foreach ($tables as $table):?> ... some elements generated ... <td><a onclick="setPortalId(<?php echo $table['id']?>);$('#file ...

Exploring the World of Html

I'm struggling with an HTML problem related to a web programming class I'm taking. The assignment involves creating a video game using HTML and JavaScript, where an image moves randomly on the screen and the player must click on it as many times ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

The function Page.render() will output a value of false

Currently, I am utilizing phantomjs to capture screenshots of multiple webpages. The code snippet below is what I have used to generate a screenshot image. var page = require('webpage').create(); page.viewportSize = { width: 1200,height: 800}; ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

Issue with the Bootstrap carousel jQuery plugin

Hi everyone, I need some help with creating a multiple items bootstrap carousel. I keep getting an error message that says "#Carousel".carousel is not a function TypeError: "#Carousel".carousel is not a function. Can anyone guide me on how to fix this issu ...

Error: The object does not contain the specified method

After deploying a web app to a remote host, I encountered an unusual error. Uncaught TypeError: Object #<error> has no method 'endsWith' Key Information: The application functions perfectly on my local machine as the host. The error ari ...

Troubles arising from JavaScript functions within vue-router

I have implemented a function to authorize users, enabling restrictions on specific components based on their permissions. The function currently works effectively with the 'beforeEnter' navigation guard in Vue Router. However, I am facing diffic ...

Reimagining the Vite proxy server functionality

/** * Function to create a list of proxies based on prefixes defined in .env.development * @param list */ export function generateProxies(list: ProxyList = []) { const result: ProxyTargetList = {}; for (const [prefix, target] of list) { const i ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

The issue I'm facing with the change handler for the semantic-ui-react checkbox in a React+Typescript project

Hey there! I'm currently facing an issue with two semantic-ui-react checkboxes. Whenever I try to attach change handlers to them, I end up getting a value of 'undefined' when I console log it. My goal is to retrieve the values of both check ...

Creating a unique Angular JS / Material / Datatables application - Proper script loading sequence required based on page context

My top two declarations placed above the closing body tag. When used in a material dropdown page, the current order of these scripts works fine. However, when I switch to my datatables page (which is a separate page), I need to swap the order of the two s ...

Incorporating jsbi into a TypeScript project while adhering to strict mode

I have been developing a TypeScript library that relies on native BigInts. While it functions perfectly in Chrome, I encountered some issues with Safari. After some research, I stumbled upon the jsbi "polyfill" that seems to solve this problem. Unfortunat ...

Displaying JSON data on an HTML page

i am currently developing a web application and i am facing an issue with retrieving data from JSON files and displaying them in table format. The problem arises when i encounter a 404 error, as i am working locally using Node.js. Edit 1: upon checking ...

Trigger a JQuery selector when a click event occurs

I'm trying to set up an event trigger when clicking on a specific class within a div. Here's what I've attempted: $("div .event").click(function() { alert($( this ).text()); }); And also tried the following: $("div").on("click", $(&a ...

Loading content from another webpage within a webpage using Ajax

I successfully implemented an Ajax chat in a PHP page and it was working perfectly. However, when I tried to integrate the chat into another page using a pop-up div (via CSS with z-index), I encountered some issues. Here is the code snippet: function sho ...

Effortlessly altering values within a dynamic key in Firebase's real-time database

I attempted to redefine the value as "pretend" using the code snippet below, but unfortunately it did not succeed. dataBase.ref().orderByChild('en_word').equalTo('pretend').set({ en_word: 'Pretend' }) ...

Is there a way to automatically update the input value when I refresh the page following a click event?

Currently, I have multiple p elements that trigger the redo function upon being clicked. When a p element is clicked, the quest[q] template is loaded onto the .form div. These templates are essentially previously submitted forms that sent values to an obj ...