'How to save current language (i18n) in localstorage (Vue)

I'm developing an app in Vue using Vue Routers and Vue $i18n plugin.
This is 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 my JS:

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 have already searched the Internet but still cannot get it.
Hope you can help me! Thanks <3



Solution 1:[1]

This is the syntax for saving in localStorage:

localStorage.setItem("name", value);

and to get and item:

localStorage.getItem("name")

see here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Solution 2:[2]

add @change event for setting the localStorage / sessionStorage and create mounted() function to load it 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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomer
Solution 2 Jozef