API

Composables

Composition API for Nuxt i18n module.

useLocalePath

The useLocalePath composable returns a function that resolves a path according to the current locale.

Example:

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

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

Type

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

useLocaleRoute

The useLocaleRoute composable returns a function that resolves the route according to the current locale.

Example:

<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>

Type

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

useSwitchLocalePath

The useSwitchLocalePath composable returns a function that allows to switch the locale.

Example:

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

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

Type

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

useLocaleHead

The useLocaleHead composable returns localized head properties for locale-related aspects.

Example:

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

Type

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

Parameters

options

An object accepting the following optional fields:

  • addDirAttribute
    Type: Boolean
    Adds a dir attribute to the HTML element. default false.
  • addSeoAttributes
    Type: boolean | SeoAttributesOptions
    Adds various SEO attributes. default false.
  • identifierAttribute
    Type: String
    Identifier attribute of <meta> tag, default 'hid'.

useSetI18nParams

The useSetI18nParams returns a function to set translated parameters for the current route. For more details on its usage see the Lang Switcher guide.

Example:

<script setup>
// fetch product from API... (red mug)

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>

Type

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

Parameters

options

Type: SeoAttributesOptions | undefined

An SeoAttributesOptions object, default undefined. See the SEO guide for more details.

useRouteBaseName

The useRouteBaseName composable returns a function that gets the route's base name.

Example:

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

<template>
  <p>route base name: {{ baseRouteName }}</p>
</template>

Type

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

useBrowserLocale

The useBrowserLocale composable returns the browser locale.

If this composable function is called on client-side, it detects the locale from the value of navigator.languages.

Else on the server side, the locale is detected from the value of accept-language header.

Type

declare function useBrowserLocale(): string | null

useCookieLocale

The useCookieLocale composable returns the cookie locale.

If this composable function is called on client-side, it detects the locale from the value of document.cookie via useCookie. else on the server side, the locale is detected from the value of cookie header.

Note that if the value of detectBrowserLanguage.useCookie is false, an empty string is always returned.

Type

declare function useCookieLocale(): Ref<string>

useTranslation

The useTranslation composable returns the translation function.

This composable is experimental and server-side only.

Example:

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

The locale is use by the translation function is the locale detected by the function defined in experimental.localeDetector option.

Type

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

defineI18nConfig

The defineI18nConfig defines a composable function to vue-i18n configuration.

This function is used to pass the createI18n options on nuxt i18n module.

For more details about configuration, see the Vue I18n documentation.

You need return vue-i18n options object that will be resolved by Promise.

Type

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

for example, define simple vue-i18n options object:

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

Parameters

loader

A function that is the vue-i18n optionss loading.

defineI18nLocale

The defineI18nLocale defines a composable function to dynamically load locale messages.

This function is used to dynamically load a locale with lazy-load translations.

You can use at JavaScript and TypeScript extension formats.

You need return locale messages object that will be resolved by Promise.

Type

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

for example, locale loading with fetch:

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

Parameters

loader

A function that is the dynamic locale messages loading, that has the following parameters:

  • locale
    Type: Locale
    A target locale that is passed from nuxt i18n module. That is passed when the locale is switched in the following cases:
    • when you switch the locale with setLocale.
    • when the locale is switched with <NuxtLink>. for example, the route path resolved by useSwitchLocalePath or $switchLocalePath.

defineI18nLocaleDetector

The defineI18nLocaleDetector defines a composable function to detect the locale on the server-side.

The locale detector function is used to detect the locale on server-side. It's called per request on the server.

You need return locale string.

This composable is experimental. You need to configure filepath to experimental.localeDetector option.

Type

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

An example of a locale detector:

// Detect based on query, cookie, header
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
})

In the locale detector function, you can use @intlify/h3 utilites, these are auto imported.

Parameters

detector

A function that is the locale detector, that has the following parameters:

  • event
    Type: H3Event
    An H3 event. see details H3 API docs
  • config
    Type: { defaultLocale: Locale; fallbackLocale: FallbackLocale; }
    A locale config that is passed from Nitro. That has the below values:
    • defaultLocale: This value is set to the defaultLocale option of Nuxt i18n. If unset, it is set to the locale option loaded from the Vue I18n configuration (i18n.config file set on the vueI18n option). If neither of these are set, the default value of 'en-US' is used.
    • fallbackLocale: This value is set to the fallbackLocale option loaded from the Vue I18n configuration (i18n.config file set on the vueI18n option). If no fallback locale has been configured this will default to false.

Copyright © 2024