1. 安装 i18n 模块
首先,你需要安装 @nuxtjs/i18n
模块:
2. 配置 nuxt.config.js
在 nuxt.config.js
中配置 i18n 模块:
export default {
// 其他配置项...
modules: [
'@nuxtjs/i18n',
],
i18n: {
locales: [
{ code: 'zh', iso: 'zh-CN', file: 'zh.js' },
{ code: 'en', iso: 'en-US', file: 'en.js' }
],
defaultLocale: 'zh',
vueI18nLoader: true,
lazy: true,
langDir: 'locales/',
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'i18n_redirected',
alwaysRedirect: true,
fallbackLocale: 'zh'
}
}
}
3. 创建语言文件
在 locales
目录下创建语言文件 zh.js
和 en.js
:
locales/zh.js
export default {
messages: {
welcome: '欢迎来到我们的网站!',
about: '关于我们'
}
}
locales/en.js
export default {
messages: {
welcome: 'Welcome to our website!',
about: 'About Us'
}
}
4. 在页面或组件中使用 i18n
在需要切换语言的页面或组件中使用 $t
方法来获取翻译内容:
pages/index.vue
<template>
<div>
<h1>{{ $t('welcome') }}</h1>
<p>{{ $t('about') }}</p>
<button @click="switchLocale('zh')">中文</button>
<button @click="switchLocale('en')">English</button>
</div>
</template>
<script>
export default {
methods: {
switchLocale(locale) {
this.$i18n.setLocale(locale)
}
}
}
</script>
<style scoped>
/* 你的样式 */
</style>
5. 运行项目
现在你可以运行项目并测试语言切换功能:
总结
- 安装并配置
@nuxtjs/i18n
模块。 - 创建语言文件并定义翻译内容。
- 在页面或组件中使用
$t
方法和$i18n.setLocale
方法来实现语言切换。
纠错
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in │ │ E:\项目\链云展\lianyunzhan-front\node_modules@nuxtjs\i18n\package.json报错了
这个错误通常是因为 @nuxtjs/i18n 模块的 package.json 文件中没有正确配置 exports 字段,导致模块无法被正确加载。以下是一些解决方法:
1. 更新 @nuxtjs/i18n 模块
确保你使用的是最新版本的 @nuxtjs/i18n 模块。你可以通过以下命令更新模块:npm update @nuxtjs/i18n
2. 删除 node_modules 并重新安装依赖
有时候,删除 node_modules 目录并重新安装所有依赖可以解决这个问题:
3. 检查 package.json 文件
确保你的 package.json 文件中正确配置了 @nuxtjs/i18n 模块的版本。例如:
4. 手动检查 @nuxtjs/i18n 的 package.json 文件
打开 node_modules/@nuxtjs/i18n/package.json 文件,检查是否有 exports 字段。如果没有,可以尝试手动添加一个简单的 exports 字段,但这不是一个推荐的做法,因为这可能会导致其他问题。
5. 使用兼容版本
如果你使用的是 Nuxt 2,确保你安装的 @nuxtjs/i18n 版本与 Nuxt 2 兼容。例如,Nuxt 2 可以使用 @nuxtjs/i18n 的 6.x 版本:
总结
更新 @nuxtjs/i18n 模块到最新版本。
删除 node_modules 并重新安装所有依赖。
确保 package.json 文件中正确配置了 @nuxtjs/i18n 模块的版本。
检查 @nuxtjs/i18n 的 package.json 文件是否有 exports 字段。
使用与 Nuxt 2 兼容的 @nuxtjs/i18n 版本。
清除 npm 缓存并重新安装依赖。
踩坑补充
nuxt项目专属问题:
1.场景:当你的项目为创建文件动态生成路由时,创建index.vue文件,打开该页面刷新页面后路由上会出现以下问题。
/bilingualExhixxxx?routerId=xx&subjectLanguage=xxx
/bilingualExhixxxx/?routerId=xx&subjectLanguage=xxx
虽然不影响正常使用,但当你在当前执行了国际化语言切换this.$i18n.setLocale(locale)时,想同步修改路由参数,会出现虽然语言切换成功,但路由参数切换失败问题。
解决方案:
在全局路由守卫页面通过正则移除路径末尾斜杠
const normalizedPath = to.path.replace(/\/+$/, ''); // 移除路径末尾的多余斜杠
if (to.path !== normalizedPath && to.path !== '/') {
next({ ...to, path: normalizedPath });
} else {
next();
}
2.场景:项目为局部国际化语言,当从非国际化语言页面跳转至国际化语言页面时,会出现两种情况;
-
页面完成了国际化语言的转换,但是页面内$t('XXX')的静态资源未实现更新,控制台打印时,输出XXX字样的字符串,而不是配置的对应语言的静态资源
-
页面只能完成配置的默认国际化语言的转换,默认语言的静态资源可以同步更新,其他语言无法实现静态资源的同步更新
解决方案:
配置一套在国际化语言页面强制刷新翻译数据的方法
plugins/utils/i18n.js
// plugins/vue-i18n.js
import Vue from 'vue'
// 此处不能为 @nuxtjs/i18n, 会报一些配置错误,安装@nuxtjs/i18n这个依赖的按照下面这样写也没有影响
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export const loadLocaleMessages = () => {
const locales = require.context('~/locales', true, /[A-Za-z0-9-_,\s]+\.js$/i)
const messages = {}
locales.keys().forEach(key => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i)
if (matched && matched.length > 1) {
const locale = matched[1]
messages[locale] = locales(key)
}
console.log(key,'as-do-asod-oas-do-aosd-',matched,messages.default)
})
return messages
}
export default async ({ app }) => {
const messages = await loadLocaleMessages()
app.i18n.setLocaleMessage(app.i18n.locale, messages[app.i18n.locale])
}
在需要的地方调用这个方法:
methods: {
async refreshTranslations() {
const messages = await loadLocaleMessages()
this.$i18n.setLocaleMessage(this.$i18n.locale, messages[this.$i18n.locale].default)
}
}