1、安装@nuxtjs/i18n
注意版本兼容 将 @nuxtjs/i18n 安装为项目的开发依赖项:
npx nuxi@latest module add @nuxtjs/i18n
2、项目引入i18n模块
将 @nuxtjs/i18n 添加到您的 nuxt.config 模块中:
项目根目录 nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n']
})
3、配置i18n选项
通过在 nuxt.config.ts 根级别使用 i18n 属性来设置模块选项
注:这里是我个人配置的选项。
- vueI18n: ‘~/i18n/i18n.config.ts’ 和vscode setting.json
“i18n-ally.enabledParsers”: [“json”,“ts”,“yaml”],这里如果不配置,能运行但是vscode可能会报错找不到en字典错误或相关找不到错误- 在项目根目录新建i18n文件夹
然后在文件夹i18n文件夹内再新建locales文件夹和i18n.config.ts文件
大概就是i18n->locales i18n->i18n.config.ts- 再配置i18n选项
- nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxtjs/i18n'],
i18n: {
strategy: "prefix_except_default",
// 可选: prefix(路径前缀)、prefix_and_default、prefix_except_default、no_prefix
defaultLocale: "zh", // 默认语言
locales: [
{ code: "zh", name: "简体中文", file: "zh-Hans.json" },
{ code: "en", name: "English", file: "en.json" },
],
lazy: true, // 懒加载翻译文件
langDir: "locales", // 翻译文件目录
detectBrowserLanguage: {
// 自动检测浏览器语言
useCookie: true,
cookieKey: "i18n_redirected",
redirectOn: "root", // 根路径重定向
},
// 高级配置
vueI18n: '~/i18n/i18n.config.ts'
}
})
- i18n.config.ts
import zh from './locales/zh-Hans.json'
import en from './locales/en.json'
export default defineI18nConfig(() => ({
legacy: false, //默认legacy旧 api,false使用组合式api
locale: 'zh',
fallbackLocale: 'zh',
//如果没有本地化与浏览器的语言环境匹配,则使用此作为后备
messages: {
zh,
en
// zh: {
// welcome: 'Bienvenue',
// nav: { n1: "菜单", n2:"菜单2" }
// }
}
}))
4、应用国际化字典
和通用一样 模版和变量使用字典
const { t, locale, locales, setLocale, getLocaleCookie } = useI18n();
const localePath = useLocalePath();
//useLocalePath() 组合式函数返回一个函数,该函数根据当前语言环境解析路径
const localeCookie = getLocaleCookie();
//从存储的语言 Cookie 中返回语言代码
setLocale("zh");
//将应用的语言切换到指定的语言代码。如果启用了 useCookie 选项,语言 Cookie 将会被更新为新值。如果启用了前缀(strategy 除了 no_prefix),将导航到新语言的路由。
const title = t('title') //变量用法
//切换页面语言
const switchLanguage = () => {
const path = switchLocalePath(locale.value);
if (path) {
navigateTo(path);
}
};
//变量模版就用计算属性热更新
const title = computed(() => [
{
title: t("title")
}
])
<!--模版用法-->
<div>{{$t('title')}}</div>
<template>
<NuxtLink :to="localePath('index')">{{ $t('home') }}</NuxtLink>
<!-- 或者 -->
<NuxtLinkLocale to="/">{{ $t('home') }}</NuxtLinkLocale>
</template>