• 接口文档
    • 接口列表
      • 初始化 I18n 运行时
        • initI18n(localesConfig: object): I18n
      • 获取 I18n 运行时
        • getI18nInstance(): I18n
      • I18n 接口
        • t(key: string, params: object): string
        • getLocale(): string
        • setLocale(currentLocale: string): void
        • getFallbackLocale(): string
        • onLocaleChange(handler: (currentLocale: string) => void): object

    接口文档

    miniprogram-i18n API 是运行时在 JavaScript 侧操作 i18n 的接口。

    接口列表

    • initI18n(localesConfig: object): I18n
    • getI18nInstance(): I18n
    • t(key: string, params: object): string
    • getLocale(): string
    • setLocale(currentLocale: string): void
    • getFallbackLocale(): string
    • onLocaleChange(handler: (currentLocale: string) => void): object

    初始化 I18n 运行时

    initI18n(localesConfig: object): I18n

    app.js 调用 initI18n 来加载 i18n 文本并指定默认语言。若未进行指定,i18n运行时将默认从 /i18n/locales.js 中读取文本及配置。

    1. // src/app.js
    2. import { initI18n } from '@miniprogram-i18n/core'
    3. import locales from '/i18n/locales.js'
    4. initI18n(locales)
    5. App({})

    获取 I18n 运行时

    getI18nInstance(): I18n

    该接口会返回 I18n 运行时实例。

    1. import { getI18nInstance } from '@miniprogram-i18n/core'
    2. const i18n = getI18nInstance()
    3. i18n.t('key')

    I18n 接口

    以下五个接口用来获取或操作 I18n,均可在 I18n 实例或 拥有 I18n Behavior 的组件或 I18nPage 上进行调用。通过组件直接访问成员函数:

    1. import { I18n } from '@miniprogram-i18n/core'
    2. Component({
    3. behaviors: [I18n],
    4. attached() {
    5. this.t('key')
    6. this.getLocale() // en-US
    7. this.setLocale('zh-CN')
    8. this.getFallbackLocale() // zh-CN
    9. this.onLocaleChange((currentLocale) => {
    10. console.log('Locale changed to', currentLocale)
    11. })
    12. }
    13. })

    或从 I18n 实例调用:

    1. import { I18n } from '@miniprogram-i18n/core'
    2. const i18n = getI18nInstance()
    3. i18n.t('key')
    4. i18n.getLocale() // en-US
    5. i18n.setLocale('zh-CN')
    6. i18n.getFallbackLocale() // zh-CN
    7. i18n.onLocaleChange((currentLocale) => {
    8. console.log('Locale changed to', currentLocale)
    9. })

    t(key: string, params: object): string

    最主要的翻译函数,通过该函数可以获得预先定义的 i18n 文本。

    getLocale(): string

    获取当前设置的语言。默认语言应在 gulp 构建脚本中配置,详见 Gulp插件配置文档。

    setLocale(currentLocale: string): void

    设置当前语言。该值应与 i18n 定义文件名相对应。

    getFallbackLocale(): string

    获取备选语言。该值在构建脚本中进行配置,一旦设置之后无法在运行时通过接口修改。详见 Gulp插件配置文档。

    onLocaleChange(handler: (currentLocale: string) => void): object

    当前语言被修改时触发的事件回调。返回值 object,可通过返回值对象取消事件监听。

    1. const event = i18n.onLocaleChange(() => {})
    2. event.off()