首页 > 解决方案 > 如果找不到完整的关键路径,我可以让 VueI18n 在关键路径上回退吗?

问题描述

如果没有找到它,是否有可能VueI18n退回到较短的键。

这方面的一个例子可能是,我有以下消息:

{
   en: {
      "hello": "This is the fallback message!",
      "admin.hello": "This is some other message for another context"
   }
}

下面的代码说明了结果应该是什么:

{{ $t("does.not.exists.hello") }} // should fallback on hello, so the result will be "This is the fallback message!"
{{ $t("admin.hello") }} // Message exists so the result should be "This is some other message for another context"

{{ $t("hello") }} // Message exists so the result should be "This is the fallback message!"

标签: vue.jsinternationalization

解决方案


好吧,我要禁食,带着这个问题。MissingHandler 对此很有用。

代码示例变成了这样:Vue.use(VueI18n)

// 使用选项创建 VueI18n 实例

export default new VueI18n({
    locale: 'en', // set locale
    silentTranslationWarn: true,
    missing: (locale: Locale, key: Path, vm?: Vue) => {
        if(key.includes(".")) {
            let newKey = /\.(.+)/.exec(key)[1];
            console.log(newKey)
            return vm.$t(newKey) as string
        }
        return key
    },
    //formatter: new CustomFormatter(),
    fallbackLocale: 'en',
    messages // set locale messages
})

推荐阅读