The LanguageSwitcher component allows the user to determine the default language value.
src/views/Login.vue
You can also add the language switching component to your other pages. The following example shows the use of the LanguageSwitcher component on the Login.vue page.
src/i18n/translation.js
import i18n from "@/i18n";
import { nextTick } from "vue";
import store from "../store";
const Trans = {
/*
* code shortened for readability
*/
async switchLanguage(newLocale) {
Trans.currentLocale = newLocale;
store.commit('SET_LOCALE', newLocale);
cookies.set("lang", newLocale); // we user cookies
document.querySelector("html").setAttribute("lang", newLocale);
},
/*
* code shortened for readability
*/
}
src/views/Login.vue
<template>
<div>
<languageswitcher></languageswitcher>
</div>
</template>
src/views/Login.vue
import LanguageSwitcher from "@/components/LanguageSwitcher.vue";
export default {
components: { LanguageSwitcher },
}
The default locale is saved in the browser's local storage called cookies after the user logs in. If the user visiting the application has previously selected a local language, this value is obtained from cookies, if it cannot be found in cookies, it is obtained from VITE_DEFAULT_LOCALE.
src/i18n/index.js
const i18n = createI18n({
locale: import.meta.env.VITE_DEFAULT_LOCALE,
fallbackLocale: import.meta.env.VITE_FALLBACK_LOCALE,
legacy: false,
globalInjection: true,
// forceStringify: false,
messages: { tr: _tr, en: _en },
runtimeOnly: false,
pluralRules,
numberFormats,
datetimeFormats,
});
By default, all locales are stored in a JSON file by language in the src/18n/locales/ directory.
├── src
│ ├── i18n
│ │ ├── locales
│ │ │ ├── en.js
│ │ │ ├── tr.js