Lzh on GitHub

服务端翻译

在服务端进行翻译并将其作为响应返回。

你可以在服务器端进行翻译并将其作为响应返回。Nuxt i18n 模块选项中定义的语言环境消息已集成,因此你所需要做的就是配置语言环境检测器。

此功能是实验性的, 从 v8 RC8 开始支持。

定义语言环境检测器

对于服务器端翻译,你需要定义一个语言环境检测器。

Nuxt i18n 导出了 defineI18nLocaleDetector() 可组合函数来定义它。

以下是如何定义一个使用查询、cookie 和头部检测语言环境的检测器的示例:

i18n/localeDetector.ts
// 基于查询、cookie、头部进行检测
export default defineI18nLocaleDetector((event, config) => {
  // 尝试从查询中获取语言环境
  const query = tryQueryLocale(event, { lang: '' }) // 使用 `lang` 选项禁用语言环境默认值
  if (query) {
    return query.toString()
  }

  // 尝试从 cookie 中获取语言环境
  const cookie = tryCookieLocale(event, { lang: '', name: 'i18n_locale' }) // 使用 `lang` 选项禁用语言环境默认值
  if (cookie) {
    return cookie.toString()
  }

  // 尝试从头部 (`accept-header`) 获取语言环境
  const header = tryHeaderLocale(event, { lang: '' }) // 使用 `lang` 选项禁用语言环境默认值
  if (header) {
    return header.toString()
  }

  // 如果到此时无法解析语言环境,则使用传递给函数的语言环境配置的 `defaultLocale` 值进行解析
  return config.defaultLocale
})

语言环境检测器函数用于在服务器端检测语言环境。它在服务器上按请求调用。

当你定义语言环境检测器时,你需要将语言环境检测器的路径传递给 experimental.localeDetector 选项。

以下是在 Nuxt 应用程序中直接定义的语言环境检测器配置示例:

nuxt.config.ts
export default defineNuxtConfig({
  i18n: {
    experimental: {
      localeDetector: 'localeDetector.ts'
    }
  }
})

有关 defineI18nLocaleDetector() 定义的语言环境检测器函数的详细信息,请参阅 此处

eventHandler 上的 useTranslation()

要在服务器端进行翻译,你需要调用 useTranslation()

示例:

// 你需要定义 `async` 事件处理程序
export default defineEventHandler(async event => {
  // 调用 `useTranslation`,它将返回翻译函数
  const t = await useTranslation(event)
  return {
    // 使用语言环境消息的键调用翻译函数,
    // 翻译函数有一些重载
    hello: t('hello')
  }
})
对于翻译函数的键,你可以指定 nuxt.config 中 nuxt-i18n 选项中设置的语言环境消息,或者 i18n.config 消息中加载的语言环境。