Reputation: 567
I'm using vue-i18n
for my translations and it works great! But when I'm using the this.$t()
function inside the data
function of a single file component the translation is not working.
<template>
<VFooter
app
height="auto"
color="secondary">
<VLayout
justify-center
row
wrap>
<VBtn
v-for="link in links"
:key="link.name"
:to="{ name: link.name }"
flat
round
active-class>
{{ link.label }}
</VBtn>
<VFlex
py-3
text-xs-center
xs12>
©{{ currentYear }} — <strong>{{ $t('site_name') }}</strong>
</VFlex>
</VLayout>
</VFooter>
</template>
<script>
export default {
name: 'TheSiteFooter',
data() {
return {
links: [
{ name: 'what-is-pinshop', label: this.$t('footer.what_is_pinshop') },
{ name: 'contact-us', label: this.$t('footer.contact_us') },
{ name: 'cookie-policy', label: this.$t('footer.cookie_policy') },
{ name: 'privacy-policy', label: this.$t('footer.privacy_policy') },
{ name: 'terms-and-conditions', label: this.$t('footer.terms_and_conditions') },
],
};
},
computed: {
currentYear() {
return new Date().getFullYear();
},
},
};
</script>
But, if I instead change data
with only the key of translation and then in my template use e.g {{ $t('footer.what_is_pinshop') }}
the translation loaded is correct. Why does this happen? I'm using the beforeEnter
router guard to change the translation. I have followed this example.
UPDATE
If I put links
as a computed property the translation works. So why it does not happen only in data
property? I also tried with this.$i18n.t()
, but nothing
Upvotes: 0
Views: 832
Reputation: 3536
This is, because of the vue lifecycle. Push your link
data into the array by using the created
hook. Keep you data
(model) clean and do not call functions in it. You call this up before all events and reactivity mechanisms have ever been registered.
lifecycle: https://v2.vuejs.org/v2/guide/instance.html
if you're interested how it works: https://github.com/kazupon/vue-i18n/tree/dev/src
UPDATE I just showered and thought again about it. In depth this is because of the reactivity mechanism. You initialize your data with a function and vue cannot detect if the returned value has changed. See how it works: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty in vue 3 this is replaced by https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Upvotes: 1