nuxt3 nuxtjs/i18n 配置

安装、引入

npm install @nuxtjs/i18n@next --save-dev
-------------------------
nuxt.config.ts
export default defineNuxtConfig({
  ...
  modules: [
    "@nuxtjs/i18n",
  ],
})

配置

配置位置

直接在文件中配置

export default defineNuxtConfig({
  modules: [
    '@nuxtjs/i18n',
  ],
  i18n: {
    // 配置内容
  }
})
export default defineNuxtConfig({
  modules: [
    [
      '@nuxtjs/i18n',
      {
        // 配置内容
      }
    ]
  ]
})

通过vueI18n属性可以设置一个配置文件,写i18n插件的一些配置项

export default defineNuxtConfig({
  modules: [
    "@nuxtjs/i18n",
  ],
  i18n: {
    vueI18n: "./nuxt-i18n.js", // 配置文件
  },
})

// nuxt-i18n.js
export default {
  // 配置内容
}

配置策略prefix_except_default url区分路由

如果目前有路由

  • http://localhost:3000/

  • http://localhost:3000/detail

将被转换为

  • http://localhost:3000/

  • http://localhost:3000/en

  • http://localhost:3000/detail

  • http://localhost:3000/en/detail

name也会从xxx改为xxx___cnxxx___en

export default defineNuxtConfig({
  i18n: {
    locales: ["cn", "en"],
    defaultLocale: "cn",
    customRoutes: "page",
    strategy: "prefix_except_default",

    detectBrowserLanguage: {
      fallbackLocale: "cn",
      useCookie: true,
      cookieKey: "language",
      redirectOn: "no prefix", // recommended
      cookieDomain: cookieDomain(),
      alwaysRedirect: true,
    },
    vueI18n: "./build/nuxt-i18n.js", // custom path example
  },
})
import { lang as cn } from "../locales/lan-zh";
import { lang as en } from "../locales/lan-en";

export default {
    legacy: false,
    warnHtmlMessage: false,
    messages: {
        cn: {
            lang: cn,
        },
        en: {
            lang: en,
        },
    },
};

配置介绍

  • legacy:设置为false的话,$i18n是全局Composer实例,否则是一个全局VueI18n实例

  • locales:支持的语言列表,可以是数组或对象

    • code:(必填)-区域设置的唯一标识符

    • iso:用于SEO优化

    • file:国际化对应文件(messages)

配置策略no_prefix cookie属性区分

如下配置完后,i18n会默认获取cookie中存储的language字段,根据字段值是"cn"还是"en"处理国际化
在需要切换国际化时,通过$i18n.setLocaleCookie("en")切换

export default defineNuxtConfig({
  i18n: {
    locales: ["cn", "en"],
    defaultLocale: "cn",
    strategy: "no_prefix",

    detectBrowserLanguage: {
      fallbackLocale: "cn",
      useCookie: true,
      cookieKey: "language",
      redirectOn: "no prefix", // recommended
      cookieDomain: cookieDomain(),
    },
    vueI18n: "./build/nuxt-i18n.js", // custom path example
  },
})
import { lang as cn } from "../locales/lan-zh";
import { lang as en } from "../locales/lan-en";

export default {
    legacy: false,
    warnHtmlMessage: false,
    messages: {
        cn: {
            lang: cn,
        },
        en: {
            lang: en,
        },
    },
};

配置介绍

  • alwaysredirecttrue总是重定向到存储在cookie中的值,false仅在第一次访问时

  • fallbackLocale:cookie中没有设置值的话,默认使用此致(并不是默认setCookie此值)

  • redirectOnall-检测所有path root-仅检测根路径"/" no_prefix-"root"宽松版

  • useCookie:路由策略下才会用到该参数:true被重定向到首选区域后设置cookie。 false每次重定向

  • cookieKeycookie的名称

  • cookiecrossorigincookiedomain配置

注意问题

当修改过detectBrowserLanguage.cookieKey后,不要相信i18n中setLocaleCookie自动修改cookiecookieKey对应的值的效果,他会偶尔抽风,错误的去设置默认cookieKeyi18n_redirected

我的解决方案

手动设置language开解决该问题

  1. 通过plugins在每次打开页面时更新language的值

    // 更新i18n
    export default defineNuxtPlugin((nuxtApp) => {
        let language = useCookie("language", getCookieInfo()); // getCookieInfo用于获取i18n配置上相同的domain等信息【{domain:'xxx'}】
        if (!language.value) language.value = "cn";
        nuxtApp.$i18n.setLocale(language.value);
    });
    
    
  2. setLanguage时,调用$i18n.setLocaleCookie同时手动修改language的值

    /**
     * 设置国际化
     * @param {string} val 国际化的值
     * @returns undefined
     */
    export function setLanguage(val) {
        if (!["cn", "en"].includes(val)) return;
        let language = useCookie("language", getCookieInfo());
        language.value = val;
        const nuxtData = useNuxtApp();
        nuxtData.$i18n.setLocaleCookie(val);
        // window.location.reload();
    }
    

    需求允许的情况下,修改后调用window.location.reload就更好啦

    注意事项:

    (仅打包后会出现异常)不要在nuxt.config.ts中将国际化页面配置成静态渲染(预渲染)页面,该选项会在打包时将页面预渲染成默认语言的html文件,访问该页面时服务端会直接返回当前html(因为与渲染会将函数执行,导致服务端返回的一直是默认语言的页面),最终导致页面语言和排版混乱

    附:预渲染页面配置方法如下

    export default defineNuxtConfig({
      nitro: {
        prerender: {
            crawlLinks: true,
            routes: ["/","/detail"], // 预渲染的页面
        },
      }
    })
    

你可能感兴趣的:(nuxt3,vue,JS,javascript)