【问题标题】:Nuxt3 & Nuxt I18n Plugin doesn't detect Browser language preference & Deployement issueNuxt3 和 Nuxt I18n 插件没有检测到浏览器语言偏好和部署问题
【发布时间】:2022-12-14 13:27:47
【问题描述】:

实际上使用 Nuxt3 RC Documentation 和它的专用插件 Nuxt/I18n Documentation

我遇到了两个问题:

第一个问题是我没有检测到浏览器偏好语言,它总是回退到默认的本地语言,我看到直到我用 useSwitchLocalePath() 更改语言后才设置 cookie 注意:切换语言有效,我有 /en 和 cookie

我的第二个问题是,当我使用 nuxi generate 生成我的静态站点时,一旦部署了网站,转到我的根路径 '/' 发回 404,但我的本地主机处理该路径并重定向到 .../en for例如,问题可能出在我使用的前缀策略,因为我在下面的文档中阅读过

This strategy combines both previous strategies behaviors, meaning that you will get URLs with prefixes for every language, but URLs for the default language will also have a non-prefixed version (though the prefixed version will be preferred when detectBrowserLanguage is enabled.

这是我的nuxt.config.js 文件

export default defineNuxtConfig({
  modules: [
     '@nuxtjs/i18n'
  ],
  i18n: {
    defaultLocale: "en",
    baseUrl: 'https://*****',    
    strategy: "prefix",
    detectBrowserLanguage: {      
      useCookie: true,      
      cookieKey: 'i18n_lang',      
      redirectOn: 'root',  
    },
    locales: [
      { code: 'en', iso: "en-US", name: "ENGLISH", file: 'en-US.json', isCatchallLocale: true }, 
      { code: 'fr', iso: "fr-FR", name: "FRENCH", file: 'fr-FR.json' }],
    lazy: true, 
    langDir: 'locales'
  }
})

为了尝试一下,我将 Chrome 配置为法语,将 Firefox 配置为英语 要使用浏览器首选项设置语言,我在插件文件夹 launch.client.js 中添加了一个文件

import { getCookie } from "../utils/cookie"

const LANG_COOKIE_NAME = "i18n_lang"
const LANG_COOKIE_DATE = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toGMTString()
const LANG_COOKIE_SAME_SITE = "Lax"

export default defineNuxtPlugin((nuxtApp) => {
  if (getCookie(LANG_COOKIE_NAME) !== undefined) return

  let browserLangPref = navigator.language
  const { locales, setLocale } = nuxtApp.$i18n
  const availableLocales = [...locales.value.map(el => el.code), ...locales.value.map(el => el.iso)]

  if (!availableLocales.includes(browserLangPref)) browserLangPref = "en"

  document.cookie = `${LANG_COOKIE_NAME}=${browserLangPref}; expires=${LANG_COOKIE_DATE}; path=/; SameSite=${LANG_COOKIE_SAME_SITE}`;
  setLocale(browserLangPref)
})

此解决方法有效,但似乎不是一种干净的方法

对于部署问题,我切换回前缀和默认策略,使用我的插件一切正常

我只是问自己这是否不是一个好方法,也许我只是不理解文档中的某些内容

也许有人有这个用例的功能回购,我可以检查一下。

【问题讨论】:

    标签: nuxt.js vuejs3 nuxtjs3 nuxt-i18n


    【解决方案1】:

    如果你使用服务器端渲染,我会使用这样的东西:

    if (process.server) {
          const nuxtApp = useNuxtApp()
          const reqLocale = nuxtApp.ssrContext?.event.node.req.headers['accept-language']?.split(',')[0]
          if (reqLocale) {
            return reqLocale
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      相关资源
      最近更新 更多