0

我正在使用vue-i18n我的翻译,效果很好!但是当我在单个文件组件的函数中使用该this.$t()函数时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>
        &copy;{{ 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(),但没有

4

1 回答 1

1

这是因为 vue 的生命周期。link使用created钩子将数据推送到数组中。让你data(模型)保持干净,不要在其中调用函数。在注册所有事件和反应机制之前调用它。

生命周期:https ://vuejs.org/v2/guide/instance.html

如果您对它的工作原理感兴趣:https ://github.com/kazupon/vue-i18n/tree/dev/src

更新 我刚洗了澡,又想了想。深入地说,这是因为反应机制。您使用函数初始化数据,vue 无法检测返回值是否已更改。看看它是如何工作的:https ://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty in vue 3 这被https://developer.mozilla.org/de/docs取代/Web/JavaScript/参考/Global_Objects/代理

于 2019-01-19T13:52:52.080 回答