【问题标题】:Using vue-i18n to translate the default value for a Vue component prop使用 vue-i18n 转换 Vue 组件 prop 的默认值
【发布时间】:2020-08-07 01:41:30
【问题描述】:

我正在使用vue-i18n 在我的应用程序中处理本地化。我需要将本地化应用于组件道具的默认值:

export default {
  name: 'ExampleComponent',
  props: [{
    prompt: {
      required: false,
      type: String,
      default: $t('example.prompt.default')
   }]
}

$t 显然不在所示范围内,但似乎此时正在评估道具的默认值,this 也不是组件本身,因此this.$t 也未定义。

使用 VueI18n 转换道具的default 值的最佳方法是什么?

【问题讨论】:

    标签: javascript vue.js vue-i18n


    【解决方案1】:

    您可以在回调函数中访问$t,因为回调是在创建的组件的上下文中评估的。

    prompt: {
      required: false,
      type: String,
      default: function () {
        this.$t('example.prompt.default')
      }
    }
    

    这里的缺点是undefinedbeforeCreate 生命周期钩子中的值将是undefined。如果您在那里需要它,那么最好的办法是将默认值设置为 i18n 定义的键(example.prompt.default),并改用this.$t(this.prompt)

    【讨论】:

    • 这不起作用。我认为您在默认函数中缺少 return 语句。它也不响应语言环境的变化。
    • 它确实有效,或者尝试 es6 语法:默认:() => this.$t('error.couldNotGetData')
    • 我收到Property '$t' does not exist on type '{ type: StringConstructor; required: boolean; default: () => String; }'
    • 我认为这行不通,因为thisdefault 函数中不可用,根据the docs
    【解决方案2】:

    您可以从导入的位置导入 VueI18n 实例。

    import i18n from '../i18n'
    
    export default {
      name: 'ExampleComponent',
      props: [{
        prompt: {
          required: false,
          type: String,
          default: i18n.t('example.prompt.default')
       }]
    }
    

    i18ns.js

    import Vue from 'vue'
    import VueI18n from 'vue-i18n'
    
    Vue.use(VueI18n)
    
    function loadLocaleMessages () {
      const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
      const messages = {}
      locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
          const locale = matched[1]
          messages[locale] = locales(key)
        }
      })
      return messages
    }
    
    export default new VueI18n({
      locale: process.env.VUE_APP_I18N_LOCALE || 'en',
      fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
      messages: loadLocaleMessages()
    })
    
    

    【讨论】:

    • 这个解决方案的问题是它在更改语言环境时没有反应
    猜你喜欢
    • 2020-08-22
    • 2019-12-10
    • 2021-04-24
    • 1970-01-01
    • 2020-07-16
    • 2019-04-19
    • 2018-08-02
    • 2021-10-20
    • 2021-10-09
    相关资源
    最近更新 更多