0

С помощью vue add i18n добавил в только что созданный проект i18n. Файлы i18n.js и main.js не трогал. В компоненте пытаюсь изменить язык как в видео YouTube , но выдаёт ошибку. Причём если руками в i18n.js меняю locale то всё работает.

Ошибка:

runtime-core.esm-bundler.js?5c40:218 Uncaught TypeError: Cannot read properties of undefined (reading '$i18n') at Proxy.changeLocal (Header.vue?0418:14:1) at Object.onClick._cache.._cache. (Header.vue?0418:2:1) at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:155:1) at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:164:1) at HTMLDivElement.invoker (runtime-dom.esm-bundler.js?830f:366:1)

i18n.js

import { createI18n } from 'vue-i18n';

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).default;
        }
    });
    return messages;
}

export default createI18n({
    sync: true,
    locale: 'ru',
    fallbackLocale: 'en',
    messages: loadLocaleMessages(),
});

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import i18n from './i18n'

createApp(App).use(i18n).use(store).use(router).mount('#app')

Компонент , где хочу поменять язык

<template>
    <div class="header" @click="changeLocal()">
        {{ $t('message') }}
    </div>
</template>

<script>
export default {
    name: 'Header',
    setup() {
        const changeLocal = () => {
            this.$i18n.locale = 'en';
        };
        return { changeLocal };
    },
};
</script>

1 ответ 1

0

У меня, в последнем Vue3 ts приложении устроено вот так. Переменная locale прокинута в v-model <input type="radio">. Всё отлично работает.

<script lang="ts">
import { useI18n } from 'vue-i18n';

export default defineComponent({
  setup() {
    const { locale } = useI18n();

    return {
      locale,
    };
  }
});
</script>
2
  • Круто , сработало. А где ты узнал что именно так нужно его использовать. И в документации и в интернете все используют this.$i18n.locale = 'en'
    – Daniil
    31 янв 2022 в 12:31
  • Уже и не вспомнить :) 31 янв 2022 в 14:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.