指南

服务器端翻译

在服务器端进行翻译并返回响应。

您可以在服务器端进行翻译并将其作为响应返回。nuxt i18n 模块选项中定义的 locale 消息已集成,因此您只需配置 locale 检测器即可。

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

定义 locale 检测器

对于服务器端翻译,您需要定义一个 locale 检测器。

Nuxt i18n 导出了 defineI18nLocaleDetector() 组合函数用于定义检测器。

以下是一个示例,演示如何定义一个使用查询、cookie 和头部检测 locale 的检测器:

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

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

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

  // 如果 locale 到此为止无法解析,则使用传递给函数的 locale 配置中的 `defaultLocale` 值进行解析
  return config.defaultLocale
})

locale 检测器函数用于在服务器端检测 locale。它在服务器的每个请求中被调用。

当您定义 locale 检测器时,需要将 locale 检测器的路径传递给 experimental.localeDetector 选项。

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

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

有关通过 defineI18nLocaleDetector() 定义的 locale 检测器函数的详细信息,请参阅 这里

在 eventHandler 中使用 useTranslation()

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

示例:

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