我正在使用vue-i18n作为我的翻译,它工作得很好!但是,当我在单个文件组件的data函数中使用data函数时,翻译就不能工作了。
<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>但是,如果我只使用翻译键更改data,然后在模板中使用例如{{ $t('footer.what_is_pinshop') }},那么加载的翻译是正确的。这一切为什么要发生?我正在使用beforeEnter路由器保护来更改转换。我跟踪了这个例子。
更新
如果我将links作为计算属性,则翻译工作。那么,为什么它不只发生在data属性中呢?我也试过用this.$i18n.t(),但什么也没有
发布于 2019-01-19 13:52:52
这是因为vue生命周期。使用link钩子将您的created数据推入数组。保持data(模型)干净,不要调用其中的函数。在注册所有事件和反应性机制之前,您可以调用它。
生命周期:https://v2.vuejs.org/v2/guide/instance.html
如果你对它的工作方式感兴趣:https://github.com/kazupon/vue-i18n/tree/dev/src
更新--我只是冲了个澡,然后再想一想。深入地说,这是因为反应机制。使用函数初始化数据,vue无法检测返回的值是否已更改。看看它是如何工作的: vue 3中的对象/对象/定义属性,它被对象/代理取代
https://stackoverflow.com/questions/54267049
复制相似问题