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

Convert a JSON array into a new format

Here is the JSON data input provided: "rows": [ [ 1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement" ], [ 2, "ADM ...

How to switch the code from using $.ajax() to employing $.getJSON in your script

How can I convert this code from using AJAX to JSON for better efficiency? AJAX $('#movie-list').on('click', '.see-detail', function() { $.ajax({ url: 'http://omdbapi.com', dataType: 'json', d ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

Converting a table into div elements and subsequently reverting it back to its original table format

[STOP DOWNVOTING: NEW AND IMPROVED] Discovering a simple technique on stackoverflow to transform tables into divs has been quite enlightening. By assigning classes to each tag, such as: <table class="table"> the process of converting from table to ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

The output varies with each reload even though the function remains constant

Essentially, my webpage functions as an online store where the content is dynamically generated using PHP shortcodes. Here is an example of how it is structured: <?php get_header(); ?> <div id="main-content"> <div id="page-content"> ...

Can a post request be sent in Node/Express using just HTML and server-side JavaScript (Node.js)?

Can a post request be made in Node/Express using only HTML and Server-side Javascript? (HTML) <form action="/submit-test" method="post"> <input type="text" name="id"> <button type="submit">Submit</button> </form> (N ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

When working with AngularJS routing, utilize a function for the templateUrl to dynamically load the appropriate template

Can a function be used as the templateUrl in angularjs routing? The $routeProvider official documentation states: templateUrl – {string=|function()=} Check out the $routeProvider official documentation here In javascript, a function is typically def ...

Render function in Next.js did not yield anything

Recently, I came across the next.js technology and encountered an error. Can anyone help me solve this issue? What could be causing it?View image here import React from 'react' import Button from "../components/button" function HomePa ...

Executing Client-Side Function Upon Data Retrieval in a Node.js Application

Within my node.js Express application, there exists a route like this: router.get('/devices/:id/visualize', catchErrors(deviceController.visualizeDevice)); This route points to the following controller: exports.visualizeDevice = async (req, re ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

Verifying the functionality of a custom directive in Angular 2 (Ionic 2) through unit

In my ionic application, I developed a custom directive specifically for text masking, aimed at formatting phone numbers within input fields. The core functionality of this directive revolves around utilizing ngControl to facilitate the retrieval and assig ...