С помощью 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>