如何在Nuxt 3的nuxt.config.ts文件中获取i18n locale?
在Nuxt3的nuxt.config.ts中获取i18n Locale的方法
1. 获取配置里的默认Locale
如果只是需要拿到预先定义的默认locale,直接从配置对象中引用即可,推荐把i18n配置抽成单独变量,方便复用:
// nuxt.config.ts const i18nSettings = { defaultLocale: 'en', locales: [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' } ] } export default defineNuxtConfig({ i18n: i18nSettings, // 在配置的其他地方直接使用默认locale app: { head: { titleTemplate: `%s - ${i18nSettings.defaultLocale.toUpperCase()}` } } })
2. 在运行时钩子中获取当前请求的Locale
如果需要获取用户当前使用的动态locale(对应原context.app.i18n.locale),只能在运行时钩子中操作——因为nuxt.config.ts本身是构建阶段执行的,无法直接访问请求级别的变量。
客户端/服务器端通用钩子
使用app:created钩子,在应用创建时获取当前locale:
// nuxt.config.ts export default defineNuxtConfig({ i18n: { defaultLocale: 'en', locales: ['en', 'fr'] }, hooks: { 'app:created': (nuxtApp) => { const currentLocale = nuxtApp.$i18n.locale.value // 这里可根据locale执行逻辑,比如设置全局变量、调整配置等 console.log('当前活跃Locale:', currentLocale) } } })
服务器端专属钩子
如果只需要在服务器端处理请求时获取locale,使用Nitro的request钩子:
// nuxt.config.ts export default defineNuxtConfig({ i18n: { defaultLocale: 'en', locales: ['en', 'fr'] }, nitro: { hooks: { 'request': (event) => { const i18n = event.context.app.$i18n const currentLocale = i18n.locale.value console.log('服务器请求Locale:', currentLocale) // 可在这里根据locale处理请求逻辑,比如修改响应头、路由等 } } } })
注意事项
- nuxt.config.ts的顶层代码是构建时执行的,无法直接访问运行时的用户locale,必须通过上述钩子在运行时获取。
- 如果需要在组件、页面或插件中获取locale,直接使用
useI18n()组合式函数即可:const { locale } = useI18n()。
内容的提问来源于stack exchange,提问作者CBD
相关产品推荐
相关产品推荐

