My main app.js
import Vue from 'vue'
import language from './language'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en',
messages: language.messages,
})
import router from './router'
new Vue({
el: '#app',
i18n,
router,
template: '<App/>',
components: { App }
})
The language.js
export default {
messages : {
en: {
hello: 'hello!'
},
ja: {
hello: 'こんにちは!'
},
zh: {
hello: '你好!'
}
}
}
my issue is following route.js code, which I can't use this.$i18n.t('hello')
, because $i18n
is not available.
import Vue from 'vue'
import Router from 'vue-router'
export const myRouteMap = [
{
path: '/',
component: MyComponent,
redirect: '/myHome',
//name: 'Home',
name: this.$i18n.t('hello') // can't use $i18n here.
}
]
Is there anyone has a similar situation, want to use i18n at vue-route and resolved the issue?
In your example this.i18n
is not going to be defined because it is not a Vue instance in the context of that file.
Your root issue is that you are attempting to put display data in the route
's definition. This is bad practice in general and results in issues like the one you've run into.
The name
property of the route
should be a unique identifier of the route and should not change after being defined.
If you want to base a Vue instance's property off of the translated name of the route (which is still too tight a coupling for my taste) you could do that in the Vue component you specified for the route.
computed: {
title() {
return this.$i18n.t(this.$route.name);
}
}
Really, though, you should not base your display data on the route
object. Seems like it would be clearer and less work to just specify the translation message key you want to pass to this.$i18n.t
in the definition for that related property:
computed: {
title() {
return this.$i18n.t('hello');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With