Вот работающий пример смены языка, думаю, разберешься сам
Компонент Locale.vue
<template>
<div>
<v-select
v-model="locale"
:items="locales"
item-text="locale"
item-value="locale"
append-icon=""
class="locale"
>
</v-select>
</div>
</template>
<script>
import {loadLanguageAsync} from "@/locales/i18n";
import config from "@/config";
export default {
name: "Locale",
data: function () {
return {
locales: config.locales
}
},
computed: {
locale: {
get: function () {
return {locale: this.$i18n.locale}
},
set: function (locale) {
loadLanguageAsync(locale)
}
},
},
created() {
loadLanguageAsync(localStorage.getItem('lang'))
}
}
</script>
Скрипт i18n.js
Доступные языки беру из config.js
JS файлы с языками находятся в @/locales/lang/(en.js, ru.js)
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import axios from 'axios'
import config from "@/config";
import messages from "@/locales/lang/en.js"
Vue.use(VueI18n)
export const i18n = new VueI18n({
locale: "en",
fallbackLocale: "en",
messages: {
"en": messages
}
})
const loadedLanguages = ["en"]
function setLanguage(lang) {
i18n.locale = lang
document.querySelector('html').setAttribute('lang', lang)
return lang
}
export function loadLanguageAsync(lang) {
let language = lang
if (config.locales.findIndex(locale => locale.locale === lang) === -1) {
language = config.defaultLocale
}
localStorage.setItem('lang', language)
// If the same language
if (i18n.locale === language) {
return Promise.resolve(setLanguage(language))
}
// If the language was already loaded
if (loadedLanguages.includes(language)) {
return Promise.resolve(setLanguage(language))
}
// If the language hasn't been loaded yet
return import(`@/locales/lang/${language}.js`).then(
messages => {
i18n.setLocaleMessage(language, messages.default)
loadedLanguages.push(language)
return setLanguage(language)
}
)
}
Скрипт main.js
import Vue from 'vue'
import App from '@/App.vue'
import {i18n} from "@/locales/i18n";
new Vue({
render: h => h(App),
i18n,
}).$mount('#app')