Saving the current language (i18n) in local storage using VueJS

I'm working on a Vue app that utilizes Vue Routers and the Vue $i18n plugin.
Here's how I've structured my HTML:

<div class="locale-changer">
  <select v-model="this.$i18n.locale" class="btn">
    <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
  </select>
</div>

And here is the JavaScript code:

export default {
  name: "home",
  data() {
    return {
      langs: ['Español', 'English'],
      currentlang: this.$i18n.locale
    }
  },
  mounted() {
    if(localStorage.currentlang) this.currentlang = localStorage.currentlang;
  },
  watch: {
    currentlang(newLang) {
      localStorage.currentlang = newLang;
    }
  }
};

I've been scouring the web for solutions but haven't found one that works for me.
I hope someone here can assist me! Much appreciated <3

Answer №2

Implement an @change event to update and store the language preference using localStorage/sessionStorage. Additionally, create a mounted() function to load the stored language at the beginning

<template>
  <select @change="updateLanguage()" v-model="$i18n.locale">
    <option v-for="(locale, i) in locales" :key="`locale-${i}`" :value="locale">
      {{ locale.toUpperCase() }}
    </option>
  </select>
</template>

<script>
export default {
  name: "LocaleSwitcher",
  data() {
    return { locales: ["sk", "cs", "en"] };
  },
  methods: {
    updateLanguage() {
      sessionStorage.setItem("locale", this.$i18n.locale);
    },
  },
  mounted() {
    if (sessionStorage.getItem("locale")) {
      this.$i18n.locale = sessionStorage.getItem("locale");
    } else {
      sessionStorage.setItem("locale", this.$i18n.locale);
    }
  },
};
</script>

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

Guide on utilizing fs.readStream and fs.writesream for transmitting and receiving video file (.mp4) either from server to client or vice versa using Node Js

## My Attempt to Receive and Save Video Stream in .mp4 Format ## ---------- > Setting up Server Side Code > Receiving Video stream from client and saving it as a .mp4 file var express = require('express'); var app = global.app = expor ...

Tips for sending two values to a PHP file using JavaScript Ajax

I have created a code for two dropdown menus. The goal is to select values from both menus and send them to a php file using the GET method. The values should be sent to the php file only when both menus have selections made. Below is the code snippet: ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

What could be causing the net::ERR_CONNECTION_CLOSED error to occur following an ajax request?

I'm facing an issue where my code works perfectly fine on localhost, but I encounter the following error when trying to run it on a hosting platform: (failed) net::ERR_CONNECTION_CLOSED. Could someone please explain what this error signifies and p ...

Discovering the environmental variables with the help of Quasar-Dotnev

.env NODE_ENV=production API_URL=https://api.example.com webpack.config.js const dotenv = require('dotenv') module.exports = { env: dotenv, ...... } Despite configuring process.env in Router, the values from the .env file are not ...

Vue warning triggered in Jest test due to error being rethrown

I have a Vue application consisting of a page component and a nested child component that performs an asynchronous post request. When the request fails, an error is thrown and propagated to the top component (Page.vue). The top component handles all errors ...

how can you add an object to an array in react native without altering the properties of the array

In my attempt to contract an array for use in 'react-native-searchable-dropdown', I have encountered an issue while trying to push objects into the array. Here is the code snippet that I am struggling with: let clone=[]; obj={{id:8,name:'Yyf ...

Leveraging jQuery for Crafting a Quiz with True or False Questions

Exploring the most effective approach to constructing a questionnaire. Find images below for reference. The current code setup is functional but becomes lengthy after just two questions. How can I streamline this code to minimize repetition? // prevent d ...

Utilizing Page Methods

I have encountered an issue while using an ajax callback for a void method. When I try to call another method within the calling method, I get an error. Any assistance with resolving this problem would be greatly appreciated. Here is the code snippet: ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

Bridging the Gap: Creating a Seamless Connection between Rails and Vue for an

I'm a bit confused about this. When working with Rails and erb files to construct page layout, 1) what scenarios call for the use of webpacker to incorporate Vue? From my understanding, a Vue application might need to make server requests som ...

Error: WebView element type is not valid. A valid string was expected

Here is my basic React code : import React from "react"; import { Text, StyleSheet,View } from "react-native"; import { WebView } from 'react-native'; const App = () => { return( <WebView source={{ ...

Exploring methods to access specific values from an array containing multiple values using Lodash in Angular 4

Hey, I have an array that looks like this: [ 0: "Migration, MD" 1: "Lution, MD" 2: "Mover, MD" 3: "Dee" 4: "Prov10A" ] I would like to extract the values that contain the word "MD" in them. In other words, I want a result like this: [ 0: "Migratio ...

Comparing Nodes Armed with Clusters to Nodes Sporting Threads

Can you explain the key distinctions between node cluster and Threads agogo, including their respective advantages and disadvantages? From my understanding, Threads agogo creates a background thread while node cluster initiates a new process to run in th ...

What is the best way to create a percentage glyphicon star icon that reflects a decimal average rating?

I have an average rating of 4.3 and I need to create a logic to display this as 4.3 stars (4 whole stars and the 5th star partially filled). The maximum rating is out of 5. Despite referring to examples on Stack Overflow and creating a JSFiddle, I am unabl ...

indexing into a nodelist results in an undefined value

In my current code snippet, I am using the following: const modelInputs = document.getElementsByName('jpd-model') console.log(modelInputs) This code returns a NodeList of all the matching elements. However, if I modify the code to this: const m ...

Configuring git npm dependencies to aid in debugging purposes

This is my first time trying to debug a library in my application and I'm not entirely sure how to go about it. I initially installed the library with npm install @react-pdf/renderer, but debugging was proving difficult. Then, I found a useful answer ...

Is there a way to conclude an Inquirer prompt depending on the response received?

My current project involves creating an application that presents a series of questions to gather information and generate an employee profile. This application is designed to be recursive, meaning that users will have the option to exit and terminate the ...

What is the best way to set parameters for a dynamic route?

I would like to navigate to the next page with a click event using a dynamic route. The route ID is retrieved from a Vuex store. When I click, the following URL is generated: http://localhost:8080/worklist/%7Bname:'worklistDynamic',%20params:%7B ...