Reputation: 434
I am trying to import a .json file to use as the translation file.
<template>
<template v-slot:footer>
<div>{{ $t('menu.file.new.label', $i18n.locale, locale) }}</div> <--Issue outputs menu.file.new.label
</template>
</template>
<script>
import locale from '@/locales/modules/messaging.json'
export default {
data() {
return {
locale: locale
}
}
}
</script>
the locale from messaging.json does not have any errors and works if i instead added the following to the top
<i18n src="@/locales/modules/messaging.json"></i18n>
and changed the function parameters to exclude $i18n.locale
and locale
and it works. Unfortunately, this is not an option as i want to pass the data to a grandchild component. However, if i can configure the grandchild to use their grandparents translation data that works too..
how can i get either:
Thanks
Upvotes: 1
Views: 10546
Reputation: 434
I found a solution
<template>
<st-age v-bind:menus="menu" v-bind:locale="locale[$i18n.locale].menu">
<template v-slot:content>message: {{ $route.params }}</template>
<template v-slot:footer>
<div>{{ $t('menu.file.label') }}</div>
</template>
</st-age>
</template>
<script>
import menu from './menu'
import locale from '@/locales/modules/messaging.json'
export default {
data() {
return {
menu: menu,
locale: locale
}
},
i18n: {
messages: locale
},
components: {
'st-age': () => import('@/components/layout/stage/container')
}
}
</script>
<style>
</style>
locale[$i18n.locale].menu
is passing the translation data i actually need and not the entire object(which works too)
in the child component, i just pass this data as a prop to the grandchild
in the grandchild i
mounted() {
this.$i18n.setLocaleMessage(this.$i18n.locale, this.locale)
}
where this.locale
is the translation data and $t('file')
yields whatever i set as en.menu.file
in the global translation data originally imported
Upvotes: 1
Reputation: 1181
First of all, you should create a plugin like below:
src/plugins/i18n.js:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
const DEFAULT_LOCALE = 'en';
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: yourLocale || DEFAULT_LOCALE, // set locale either from localStorage or config
fallbackLocale: DEFAULT_LOCALE,
messages: require('messages.json'), // set locale messages
sharedMessages: require('other.json if exist'),
silentFallbackWarn: true,
});
export default i18n;
Then call it from main.js to globalize:
import i18n from './plugins/i18n.js';
...
new Vue({
i18n,
router,
...
render: h => h(App),
}).$mount('#app');
Then if you want to go on with custom messages, you can set it with i18n block like:
<script>
data(){
...
}
methods: ...
i18n: {
messages: require(your json path....)
}
</script>
Then you can call it like:
$t('test');
Upvotes: 2