0

我在本地化组件和视图字符串方面没有任何问题,但我锁定了一种方法来动态本地化工具栏项目(当然还有导航抽屉中的相同项目..

目前它们在 App.vue 中显示为 menuItems[i].title

    <v-toolbar-items class="hidden-xs-only">
      <v-btn flat :to="menuItems[0].link">
        <v-icon left>{{ menuItems[0].icon }}</v-icon>
        <span>{{ menuItems[0].title }}</span>
      </v-btn>

使用脚本:

    <script>
    export default {
      data () {
        return {
          appName: 'myAPP',
          sideNav: false,
          menuItems: [
            { icon: 'home', title: 'Home', link: '/home' },
            { icon: 'info', title: 'About', menu: [{ title: 'Company', link: '/company' }, { title: 'Office', link: '/office' }] },
            { icon: 'people', title: 'Members', menu: [], link: '/members' },
            { icon: 'local_library', title: 'Blog', link: '/blog' },
            { icon: 'local_grocery_store', title: 'Shopping', link: '/shopping' }
          ]
        }
      },
      methods: {
          switchLocale: function (newLocale) {
            this.$store.dispatch('switchI18n', newLocale)
          }
        }
      }
    </script>

我应该使用计算值吗?还是直接在模板中使用 $t() ?

反馈,建议和链接表示赞赏

更新

main.js

Vue.filter('translate', function (value) {
  if (!value) return ''
  value = 'lang.views.global.' + value.toString()
  return i18n.t(value)
})

语言环境/i18n/en_US

{
  "views": {
    "global": {
      "Home": "Home",
      "Section1": "Section 1",
      ..
4

1 回答 1

1

Vue 提供了过滤器来帮助我们对常用文本进行格式化。

所以我认为这将是你的选择之一。

您可以单击上面的链接按照指南设置过滤器。

编辑:

我刚刚意识到 Vue-filters 不应该像 Vue 作者所说的那样依赖于这个上下文。所以更新了我的答案如下:

然后代码将如下所示:

// create vue-i18n instance
const i18n = new VueI18n({
  locale: getDefaultLanguage(),
  messages: langs
})

// create global filter
Vue.filter('myLocale', function (value) {
  return i18n.t(value)
})

在您的视图或组件中:

<template>
    <v-toolbar-items class="hidden-xs-only">
      <v-btn flat :to="menuItems[0].link">
        <v-icon left>{{ menuItems[0].icon }}</v-icon>
        <span>{{ menuItems[0].title | myLocale }}</span>
      </v-btn>
</template> 

<script>
export default {
  data () {
    return {
      appName: 'myAPP',
      sideNav: false,
      menuItems: [
        { icon: 'home', title: 'Home', link: '/home' },
        { icon: 'info', title: 'About', menu: [{ title: 'Company', link: '/company' }, { title: 'Office', link: '/office' }] },
        { icon: 'people', title: 'Members', menu: [], link: '/members' },
        { icon: 'local_library', title: 'Blog', link: '/blog' },
        { icon: 'local_grocery_store', title: 'Shopping', link: '/shopping' }
      ]
    }
  },
  filters: {
      myLocaleWhichNotWork: function (value) {
        return this.$t(value) // this won't work because filters should not be dependent on this context
      }
    }
  }
</script>
于 2018-04-20T05:44:25.627 回答