一、安装vue-i18n

npm install vue-i18n

二、创建iI18n

在这里插入图片描述

创建文件,进行相关配置
1.在src目录下,新建locales文件夹
2.在locales文件夹中,新建 en.tszh-cn.tsi18n.ts 文件
  • en.ts :英文内容
export default {
  button: {
    confirm: 'Confirm',
    login: 'Login'
  }
}
  • zh-cn.ts :中文内容
export default {
  button: {
    confirm: '确认',
    login: '登录'
  }
}
  • i18n.ts: i18n的相关配置内容
// i18n配置
import { createI18n } from "vue-i18n";
import zhCn from "./zh-cn";
import en from "./en";

// 创建i18n
const i18n = createI18n({
  locale: localStorage.getItem("language") || "zhCn", // 语言标识
  globalInjection: true, // 全局注入,可以直接使用$t
  // 处理报错: Uncaught (in promise) SyntaxError: Not available in legacy mode (at message-compiler.esm-bundler.js:54:19)
  legacy: false, 
  messages: {
    zhCn,
    en
  }
})

export default i18n;

三、在main.ts中全局引入

import i18n from './locales/i18n'; // i18n的配置文件路径,也就是 createI18n 的文件地址

createApp(App).use(i18n).mount('#app')

四、使用

1.在 < template >中可以直接使用$t
<template>
	<div>
		<el-button type="primary" @click="toLogin">{{ $t('button.login') }}</el-button>
	</div>
</template>
2.在js中使用
import { useI18n} from 'vue-i18n';

const { t } = useI18n();
function toLogin (): void {
  alert(t('button.login'));
}

五、中英文切换

六、报错 legacy

在vite脚手架项目当中,使用vue-i18n插件进行国际化多语言时,
报错:Uncaught SyntaxError: Not available in legacy mode
在这里插入图片描述

1.问题分析:

当前的vue-i18n 版本为

“vue-i18n”: “^9.8.0”,

vue-i18n的8.x版本支持vue2.x和vue3.x
vue-i18n的9.x版本主要支持vue3.x
vue3中允许使用 Options API (legacy mode)和 Composition API 模式
但是vue-i18n的9.x版主不允许混合使用这两种模式,所以需根据vue3采用的模式来确定vue-i18n使用的模式

2.解决方案:
2.1.回退vue-i18n的版本 (不推荐)
2.2.指定vue-i18n的使用模式
在i18n的配置文件中,设置vue-i18n为Composition API 模式

allowComposition: true,

const i18n = createI18n({
  locale: localStorage.getItem("language") || "zhCn", // 语言标识
  globalInjection: true, // 全局注入,可以直接使用$t
  allowComposition: true,
  messages: {
    zhCn,
    en
  }
})
2.3.设置legacy: false
const i18n = createI18n({
  locale: localStorage.getItem("language") || "zhCn", // 语言标识
  legacy: false,
  messages: {
    zhCn,
    en
  }
})

七、特殊字符无法显示的问题

在进行中英文翻译时,如果遇到特殊的符号会无法正常显示,例如
在这里插入图片描述

示例

页面中想要显示如下一段内容:

使用${tag}的方式插入标签(tag为具体的字段值)

$t('message.testTip')

zh-cn.ts文件内容

export default {
  message: {
    testTip: '使用${tag}的方式插入标签(tag为具体的字段值)'
  }
}

en.ta

  message: {
    testTip: 'Insert tags using the ${tag} method (tags are specific field values)'
  }
结果:

在这里插入图片描述
在这里插入图片描述
${ tag } 无法被识别出来

解决方法1:

使用文字插值: {‘xxxxx’}

zh-cn.ts 文件

export default {
  message: {
    testTip: "使用{'${tag}'}的方式插入标签(tag为具体的字段值)"
  }
}

en.ts 文件

  message: {
    testTip: 'Insert tags using the {'${tag}'} method (tags are specific field values)'
  }
$t('message.testTip');
解决方法2:

动态赋值:
使用大括号来标记一个字段,如:{tag}; 然后在使用时将{tag}的部分替换成需要展示的内容

zh-cn.ts文件内容

export default {
  message: {
    testTip: '使用{flag}的方式插入标签(tag为具体的字段值)'
  }
}

en.ta

  message: {
    testTip: 'Insert tags using the {flag} method (tags are specific field values)'
  }
$t('message.testTip', { flag: '${tag}'});

八、关于动态赋值(内容替换)

翻译中的内容根据获取的变量动态替换,如图:
在这里插入图片描述
方式1:使用对象
zh-cn.ts 文件定义相关中文内容

  "message": {
    "describe": "{total} 种协议,已选 {checked} 种"
  }

en.ts 文件定义相关英文内容

 "message": {
    "describe": "{total} total, {checked} checked"
  }

对象方式:

$t('backup.describe', { total: state.count, checked: state.checkedCount })

方式2:使用数组

查看文档:https://vue-i18n.intlify.dev/guide/migration/breaking.html
In Vue I18n v9 and later, you can’t use array-like objects for list interpolation, you have to use array:
在Vue I18n v9及更高版本中,不能使用类数组对象进行列表插值,必须使用数组:

zh-cn.ts 文件定义相关中文内容

  "message": {
    "describe": "{0} 种协议,已选 {1} 种"
  }

en.ts 文件定义相关英文内容

 "message": {
    "describe": "{0} total, {1} checked"
  }

数组方式:

$t('backup.describe', [state.count, state.checkedCount])

九、遇到的问题

1.本地运行正常,但是打包后特殊字符无法转义且文字插值/动态赋值的方式无法正确展示

1.更新vue-i18n依赖

"@intlify/unplugin-vue-i18n": "^3.0.1"
 "vue-i18n": "^9.10.1",

2.在vite.config.ts中配置

import { fileURLToPath } from 'url';
VueI18n({
    include: path.resolve(path.dirname(fileURLToPath(import.meta.url)), './locale/**'),
})

注意:i18n开启预编译之后,如果翻译文件中包含HTML会报错
解决方法: 添加 strictMessage 和 escapeHtml 配置,然后转义或删除HTML实体;这里采取的方法是将HTML标签动态赋值的方式插入进去;
在这里插入图片描述
在这里插入图片描述

2.在使用 $t 时提示类型错误

2.1 报错示例:

页面可以正常显示但是编辑器标红

类型“CreateComponentPublicInstance>, { ServerConfForm: typeof ServerConfForm; ShowIpAsset: typeof ShowIpAsset; isFieldIP: typeof isFieldIP; t: typeof t; … 10 more …; getTableData: typeof getTableData; }, … 17 more …, {}>”上不存在属性“$t”。
在这里插入图片描述

相关依赖版本:

"vue-i18n": "~9.10.2",
"vue": "^3.4.37",
"typescript": "~5.6.3",
2.2 解决方式

临时解决无法识别 vue-i18n $t 的问题 https://learnku.com/vuejs/t/53080
main.ts中添加类型声明

declare module 'vue' {
  interface ComponentCustomProperties {
    $t(key: string, ...args: any[]): string;
  }
}
GitHub 加速计划 / vu / vue
108
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
9e887079 [skip ci] 1 年前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐