本篇专栏基于笔者的Vue专栏,Nuxt3系列,如有不连贯之处可查看Nuxt3系列其他文章!特此说明
一、安装插件
- i18n模块
npm install @nuxtjs/i18n --save-dev
二、配置插件
- 根目录创建
lang/
目录,作为多语言目录;
// nuxt.config.ts
export default defineNuxtConfig({
...
modules: [
[
'@nuxtjs/i18n',
{
baseUrl: "", // 正式环境域名
locales: ["zh", "ja", "en"],
defaultLocale: "zh",
vueI18n: "i18n.config.ts",
},
],
],
...
});
// i18n.config.ts
import zh from "@/lang/zh/index";
import ja from "@/lang/ja/index";
import en from "@/lang/en/index";
export default defineI18nConfig(() => ({
legacy: false, // 是否兼容之前
locale: "zh",
fallbackLocale: 'zh', // 兼容不到就用en
messages: { zh, ja, en },
}));
三、使用示例
3.1 - 切换多语言
<ul class="lang-switch-wrap">
<li v-for="(item, ii) in locals" :key="`header-nav-local-${ii}`">
<NuxtLink :to="switchLocalePath(item)">{{ $t(item) }}</NuxtLink>
</li>
</ul>
<script setup lang="ts">
const locals = ["zh", "ja", "en"];
const switchLocalePath = useSwitchLocalePath();
</script>
3.2 - setup中获取i8n
const i18n = useI18n();
console.log("当前的语言", i18n.locale.value);
四、多语言Mobile站适配
场景:PC端和移动端在同一个项目,且ui差异较大,使用传统m站去做
具体说明请查看笔者的《Nuxt3适配指南》
export default defineEventHandler(async (event) => {
// 服务端
if (event.path.indexOf("images") == -1) {
const cookies = parseCookies(event);
// 是否是移动端设备
const isMobile = /(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(<string>event.headers.get("user-agent"));
// 是否是手机端路由
const isRouterMobile = event.path.indexOf("/mobile") == -1 ? false : true;
if (isMobile && !isRouterMobile) {
let url = event.path.replace("/zh", "").replace("/en", "");
console.log("mobile route", event.path, url);
if (!cookies["i18n_redirected"] || cookies["i18n_redirected"] == "ja") {
await sendRedirect(event, `/mobile${url}`, 302);
} else {
await sendRedirect(event, `/${cookies["i18n_redirected"]}/mobile${url}`, 302);
}
return
}
if (!isMobile && isRouterMobile) {
let url = event.path.replace("/zh", "").replace("/en", "").replace("/mobile", "");
console.log("pc route", event.path, url);
if (!cookies["i18n_redirected"] || cookies["i18n_redirected"] == "ja") {
await sendRedirect(event, `${url}`, 302);
} else {
await sendRedirect(event, `/${cookies["i18n_redirected"]}${url}`, 302);
}
}
if (!cookies["i18n_redirected"]) {
let url = event.path.replace("/zh", "").replace("/en", "").replace("/mobile", "");
setCookie(event, "i18n_redirected", "ja");
await sendRedirect(event, `${url}`, 302);
return
}
}
});