Api

Nuxt

与 Nuxt 相关的 I18n 其他 API。

Nuxt 运行时应用程序上下文的扩展

以下 API 在 NuxtApp 上都可用。

$i18n

  • 类型: VueI18n | Composer

另请参阅 NuxtApp

$i18n 是 Vue I18n 的全局 Composer 或全局 VueI18n 实例。有关详情,请查看 这里

如果在 @nuxtjs/i18n 配置中将 i18n.vueI18n.legacy 选项设置为 false,则 $i18n 是一个全局 Composer 实例。否则,它是一个全局 VueI18n 实例。

使用示例:

export default defineNuxtPlugin(nuxtApp => {
  nuxtApp.$i18n.onBeforeLanguageSwitch = (oldLocale, newLocale, isInitialSetup, nuxtApp) => {
    console.log('onBeforeLanguageSwitch', oldLocale, newLocale, isInitialSetup)
  }
})

$getRouteBaseName()

$switchLocalePath()

$localePath()

$localeRoute()

$localeHead()

有关这些的更多信息,请参见 Vue 的扩展 部分。

NuxtHooks 的扩展

i18n:registerModule Hook

  • 参数:
    • registerModule (类型: ({ langDir: string, locales: LocaleObject[] }) => void)
my-module-example/module.ts
import { createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  async setup(options, nuxt) {
    const { resolve } = createResolver(import.meta.url)
    nuxt.hook('i18n:registerModule', register => {
      register({
        // langDir 路径需要被解析
        langDir: resolve('./lang'),
        locales: [
          {
            code: 'en',
            file: 'en.json',
          },
          {
            code: 'fr',
            file: 'fr.json',
          },
        ]
      })
    })
  }
})

另请参阅 扩展消息钩子