You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@nuxtjs/i18n:实现用户重定向至页面可用翻译版本

解决方案:页面未适配语言时重定向至可用翻译版本

1. 页面级配置可用语言

在每个需要限制语言的页面组件中,添加i18n.locales属性,指定该页面支持的语言代码:

<script>
export default {
  // 示例:该页面仅支持英文(en)和阿拉伯语(ar)
  i18n: {
    locales: ['en', 'ar']
  }
}
</script>

未配置该属性的页面默认支持所有语言

2. 创建全局中间件处理重定向

在项目根目录的middleware文件夹下创建check-page-locale.js文件,实现语言检测与重定向逻辑:

export default function ({ app, route, redirect }) {
  // 获取当前页面配置的可用语言列表,无配置则默认全语言支持
  const pageAvailableLocales = route.matched[0]?.components?.default?.options?.i18n?.locales || app.i18n.locales.map(l => l.code)
  const currentLocale = app.i18n.locale

  // 当前语言不在页面可用列表时触发重定向
  if (!pageAvailableLocales.includes(currentLocale)) {
    // 优先选择浏览器偏好语言(若在可用列表内),否则取第一个可用语言
    let targetLocale = app.i18n.browserLocale
    if (!pageAvailableLocales.includes(targetLocale)) {
      targetLocale = pageAvailableLocales[0]
    }

    // 构建新路由并替换语言前缀
    const newPath = route.fullPath.replace(`/${currentLocale}`, `/${targetLocale}`)
    // 提前设置目标语言,确保页面方向(ltr/rtl)同步
    app.i18n.locale = targetLocale
    // 执行重定向
    redirect(newPath)
  }
}

3. 注册全局中间件

在nuxt.config.js中配置全局中间件,让所有路由都经过该检测:

export default {
  // ...其他配置项
  router: {
    middleware: ['check-page-locale']
  },
  // ...原有i18n配置保持不变
}

4. 确保页面方向同步(可选)

为了确保页面方向(ltr/rtl)完全同步,可在根布局文件(如layouts/default.vue)中手动绑定html的dir属性:

<template>
  <html :dir="$i18n.localeProperties.dir">
    <head>
      <!-- 页面头部内容 -->
    </head>
    <body>
      <nuxt />
    </body>
  </html>
</template>

方案说明

  • 避免404跳转:用户访问未适配语言时,直接重定向到页面的可用语言版本,提升用户体验
  • 页面方向同步:通过提前设置目标语言,让nuxt/i18n自动应用对应语言的dir属性,或通过布局绑定确保方向正确
  • 全局复用逻辑:无需在每个页面重复编写检测代码,一次配置全局生效
  • 智能语言选择:优先匹配用户浏览器偏好语言,无匹配时使用页面第一个可用语言

内容的提问来源于stack exchange,提问作者MrXQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:33:17