【问题标题】:Vue - Translation in single file componentVue - 单个文件组件中的翻译
【发布时间】:2019-06-13 11:45:58
【问题描述】:

我使用vue-i18n 进行翻译,效果很好!但是当我在单个文件组件的data 函数中使用this.$t() 函数时,翻译不起作用。

 <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 路由器保护来更改翻译。我关注了this example。

更新

如果我将 links 作为计算属性,则翻译有效。那么为什么它不仅仅发生在data 属性中呢?我也试过this.$i18n.t(),但没有

【问题讨论】:

    标签: vue.js vue-router vue-i18n


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 好的,现在更清楚了。我发现一个可能的解决方案是添加而不是已经翻译的字符串。只有我翻译的关键,在我的模板中我可以使用{{ $t(link.label) }}。所以links 的数组将是:[{name: 'what-is-pinshop', label: 'footer.what_is_pinshop'}]
    • 我必须删除我的示例,因为它是错误的。但其余的都是正确的。是的,你可以这样做或使用 i18n 指令:kazupon.github.io/vue-i18n/guide/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 2011-11-28
    • 2017-08-13
    • 2019-04-18
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多