API

组合函数

Nuxt i18n 模块的组合 API。

useLocalePath

useLocalePath 组合函数返回一个根据当前语言环境解析路径的函数。

示例:

<script setup>
const localePath = useLocalePath()
</script>

<template>
  <NuxtLink :to="localePath('index')">{{ $t('home') }}</NuxtLink>
</template>

类型

declare function useLocalePath(
  options?: I18nCommonRoutingOptionsWithComposable
): (route: RawLocation | RouteLocation, locale?: Locale) => string

useLocaleRoute

useLocaleRoute 组合函数返回一个根据当前语言环境解析路由的函数。

示例:

<script setup>
const localeRoute = useLocaleRoute()
const { locale } = useI18n()
const linkPath = computed(() => {
  const route = localeRoute('blog', locale.value)
  return route != null ? route.path : '/'
})
</script>

<template>
  <NuxtLink :to="linkPath">{{ $t('blog') }}</NuxtLink>
</template>

类型

declare function useLocaleRoute(
  options?: I18nCommonRoutingOptionsWithComposable
): (route: RawLocation | RouteLocation, locale?: Locale) => Route | (RouteLocation & { href: string }) | undefined

useSwitchLocalePath

useSwitchLocalePath 组合函数返回一个允许切换语言环境的函数。

示例:

<script setup>
const switchLocalePath = useSwitchLocalePath()
</script>

<template>
  <NuxtLink :to="switchLocalePath('en')">English</NuxtLink>
  <NuxtLink :to="switchLocalePath('fr')">Français</NuxtLink>
</template>

类型

declare function useSwitchLocalePath(options?: I18nCommonRoutingOptionsWithComposable): (locale?: Locale) => string

useLocaleHead

useLocaleHead 组合函数返回与语言环境相关的本地化头部属性。

示例:

<script setup>
const i18nHead = useLocaleHead({
  addSeoAttributes: {
    canonicalQueries: ['foo']
  }
})
useHead(() => ({
  htmlAttrs: {
    lang: i18nHead.value.htmlAttrs!.lang
  },
  link: [...(i18nHead.value.link || [])],
  meta: [...(i18nHead.value.meta || [])]
}))
</script>

类型

declare function useLocaleHead(options: I18nHeadOptions): Ref<I18nHeadMetaInfo>

参数

options

一个接受以下可选字段的对象:

  • addDirAttribute
    类型Boolean
    向 HTML 元素添加 dir 属性。默认值为 false
  • addSeoAttributes
    类型boolean | SeoAttributesOptions
    添加各种 SEO 属性。默认值为 false
  • identifierAttribute
    类型String
    <meta> 标签的标识符属性,默认值为 'hid'

useSetI18nParams

useSetI18nParams 返回一个函数,用于为当前路由设置翻译参数。有关其用法的更多详情,请参阅 语言切换器指南

示例:

<script setup>
// 从 API 获取产品...(红色杯子)

const setI18nParams = useSetI18nParams({
  canonicalQueries: ['foo']
})
setI18nParams({
  en: { slug: data.slugs.en }, // slug: 'red-mug'
  nl: { slug: data.slugs.nl } // slug: 'rode-mok'
})

const switchLocalePath = useSwitchLocalePath()
switchLocalePath('en') // /products/red-mug
switchLocalePath('nl') // /nl/products/rode-mok
</script>

<template>
  <!-- pages/products/[slug].vue -->
</template>

类型

declare function useSetI18nParams(options?: SeoAttributesOptions): (locale: Record<Locale, unknown>) => void

参数

options

类型SeoAttributesOptions | undefined

一个 SeoAttributesOptions 对象,默认值为 undefined。有关更多细节,请参见 SEO 指南

useRouteBaseName

useRouteBaseName 组合函数返回一个获取路由基础名称的函数。

示例:

<script setup>
const route = useRoute()
const getRouteBaseName = useRouteBaseName()
const baseRouteName = computed(() => {
  return getRouteBaseName(route)
})
</script>

<template>
  <p>路由基础名称:{{ baseRouteName }}</p>
</template>

类型

declare function useRouteBaseName(
  options?: I18nCommonRoutingOptionsWithComposable
): (givenRoute?: Route | RouteLocationNormalizedLoaded) => string | undefined

useBrowserLocale

useBrowserLocale 组合函数返回浏览器语言环境。

如果这个组合函数在客户端调用,它会从 navigator.languages 的值中检测语言环境。

否则在服务器端,语言环境是从 accept-language 头的值中检测的。

类型

declare function useBrowserLocale(): string | null

useCookieLocale

useCookieLocale 组合函数返回 cookie 语言环境。

如果这个组合函数在客户端调用,它会通过 useCookiedocument.cookie 的值中检测语言环境。否则在服务器端,语言环境是从 cookie 头的值中检测的。

注意,如果 detectBrowserLanguage.useCookie 的值为 false,则始终返回一个 空字符串

类型

declare function useCookieLocale(): Ref<string>

useTranslation

useTranslation 组合函数返回翻译函数。

这个组合函数是实验性的,仅支持服务器端。

示例:

export default defineEventHandler(async event => {
  const t = await useTranslation(event)
  return {
    hello: t('hello')
  }
})

翻译函数使用的语言环境是通过 experimental.localeDetector 选项 中定义的函数检测的语言环境。

类型

declare function useTranslation<Schema extends Record<string, any> = {}, Event extends H3Event = H3Event>(
  event: Event
): Promise<TranslationFunction<Schema, DefineLocaleMessage>>

defineI18nConfig

defineI18nConfig 定义一个用于 vue-i18n 配置的组合函数。

该函数用于传递 createI18n 选项给 nuxt i18n 模块。

有关配置的更多细节,请参见 Vue I18n 文档

您需要返回一个 vue-i18n 选项对象,该对象将被 Promise 解析。

类型

export function defineI18nConfig<Config extends I18nOptions>(
  loader: () => Config | Promise<Config>
): () => Config | Promise<Config>

例如,定义一个简单的 vue-i18n 选项对象:

export default defineI18nConfig(() => ({
  legacy: false,
  locale: 'en',
  messages: {
    en: {
      welcome: 'Welcome'
    },
    fr: {
      welcome: 'Bienvenue'
    }
  }
}))

参数

loader

一个加载 vue-i18n 选项的函数。

defineI18nLocale

defineI18nLocale 定义一个组合函数以动态加载语言环境消息。

该函数用于动态加载语言环境,使用懒加载翻译

您可以在 JavaScript 和 TypeScript 扩展格式中使用。

您需要返回一个语言环境消息对象,该对象将被 Promise 解析。

类型

declare function defineI18nLocale<Messages = LocaleMessages<DefineLocaleMessage>, Locales = Locale>(
  loader: (locale: Locales) => Messages | Promise<Messages>
): (locale: Locales) => Messages | Promise<Messages>

例如,使用 fetch 加载语言环境:

export default defineI18nLocale(locale => {
  return $fetch(`https://your-company-product/api/${locale}`)
})

参数

loader

一个动态加载语言环境消息的函数,具有以下参数:

  • locale
    类型Locale
    从 nuxt i18n 模块传递的目标语言环境。当以以下方式切换语言环境时传递:
    • 当您通过 setLocale 切换语言环境时。
    • 当通过 <NuxtLink> 切换语言环境时。例如,通过 useSwitchLocalePath$switchLocalePath 解析的路由路径。

defineI18nLocaleDetector

defineI18nLocaleDetector 定义一个组合函数以在服务器端检测语言环境。

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

您需要返回语言环境字符串。

这个组合函数是实验性的。 您需要将文件路径配置到 experimental.localeDetector 选项

类型

type LocaleConfig = {
  defaultLocale: Locale
  fallbackLocale: FallbackLocale
}
declare function defineI18nLocaleDetector(
  detector: (event: H3Event, config: LocaleConfig) => string
): (event: H3Event, config: LocaleConfig) => string

语言环境检测器的示例:

// 基于查询、cookie、头部进行检测
export default defineI18nLocaleDetector((event, config) => {
  const query = tryQueryLocale(event, { lang: '' })
  if (query) {
    return query.toString()
  }

  const cookie = tryCookieLocale(event, { lang: '', name: 'i18n_locale' })
  if (cookie) {
    return cookie.toString()
  }

  const header = tryHeaderLocale(event, { lang: '' })
  if (header) {
    return header.toString()
  }

  return config.defaultLocale
})

在语言环境检测函数中,您可以使用 @intlify/h3 工具,这些工具会自动导入。

参数

detector

一个语言环境检测函数,具有以下参数:

  • event
    类型H3Event
    一个 H3 事件。有关详细信息,请参见 H3 API 文档
  • config
    类型{ defaultLocale: Locale; fallbackLocale: FallbackLocale; }
    从 Nitro 传递的语言环境配置。具有以下值:
    • defaultLocale:该值设置为 Nuxt i18n 的 defaultLocale 选项。如果未设置,则设置为从 Vue I18n 配置(vueI18n 选项中设置的 i18n.config 文件)加载的 locale 选项。如果这两者均未设置,则使用默认值 'en-US'
    • fallbackLocale:该值设置为从 Vue I18n 配置(vueI18n 选项中设置的 i18n.config 文件)加载的 fallbackLocale 选项。如果未配置后备语言环境,则默认值为 false