Skip to content

基于本地作用域的本地化

i18n 组件选项

"作用域和语言环境切换"中,Vue I18n 有两个作用域概念:全局作用域和本地作用域。

通常,语言环境信息(如 localemessages 等)作为 createI18n 的选项设置,并通过 app.use 进行安装。总而言之,您使用全局作用域翻译函数 $t 来进行本地化。

有时需要在组件级别进行本地化,同时仍然管理本地消息资源。在这种情况下,在组件上使用 i18n 组件选项而不是全局作用域来本地化每个本地作用域会很有用。

以下是基于本地作用域的本地化示例:

js
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'

// 将全局作用域使用的语言环境信息设置为选项
const i18n = createI18n({
  locale: 'ja',
  messages: {
    en: {
      message: {
        hello: 'hello world',
        greeting: 'good morning, world!'
      }
    },
    ja: {
      message: {
        hello: '你好,世界',
        greeting: 'おはよう、世界!'
      }
    }
  }
})

// 定义组件
const Component1 = {
  template: `
    <div id="component">
      <h1>Component1</h1>
      <p>Component1 本地消息: {{ $t("message.hello") }}</p>
      <p>回退全局语言环境消息: {{ $t("message.greeting") }}</p>
    </div>
  `,
  i18n: {
    messages: {
      en: { message: { hello: 'hello component1' } },
      ja: { message: { hello: 'こんにちは、component1' } }
    }
  }
}

const app = createApp({
  components: { Component1 }
})
app.use(i18n)
app.mount('#app')

模板:

html
<div id="app">
  <h1>Root</h1>
  <p>{{ $t("message.hello") }}</p>
  <Component1 />
</div>

输出如下:

html
<div id="app">
  <h1>Root</h1>
  <p>你好,世界</p>
  <div class="component">
    <p>Component1 本地消息: こんにちは、component1</p>
    <p>回退全局语言环境消息: おはよう、世界!</p>
  </div>
</div>

如上例所示,如果组件没有语言环境消息,则会回退到全局作用域。如此处所解释的,由于本地作用域的语言环境继承自全局作用域,因此组件使用全局作用域中设置的语言(在上述示例中:locale: 'ja'

另外,如此处所解释的,请注意,默认情况下回退到全局作用域会在控制台生成两条警告:

txt
[intlify] Not found 'message.greeting' key in 'ja' locale messages.
[intlify] Fall back to translate 'message.greeting' with root locale.

如果要使用组件语言环境进行本地化,可以使用 i18n 组件选项中的 sync: falselocale

组件共享语言环境消息

有时您可能想要导入某些组件的共享语言环境消息,而不是从全局作用域的语言环境消息回退(例如,组件的某些功能的通用消息)。

您可以使用 i18nsharedMessages 选项。

通用语言环境消息示例:

js
export default {
  en: {
    buttons: {
      save: "Save",
      // ...
    }
  },
  ja: {
    buttons: {
      save: "保存",
      // ...
    }
  }
}

组件:

js
import commonMessage from './locales/common' // 导入通用语言环境消息

export default {
  name: 'ServiceModal',
  template: `
    <div class="modal">
      <div class="body">
        <p>This is good service</p>
      </div>
      <div class="footer">
        <button type="button">{{ $t('buttons.save') }}</button>
      </div>
    </div>
  `,
  i18n: {
    messages: { ... },
    sharedMessages: commonMessages
  }
}

如果指定了 sharedMessages 选项以及 messages 选项,则这些消息将合并到目标组件的 VueI18n 实例的语言环境消息中。