vue2-使用vue-i18n搭建多语言切换环境(有补充vue3)

发布时间:2026/9/10 9:26:50
vue2-使用vue-i18n搭建多语言切换环境(有补充vue3) 安装注意vue2.0要用8版本的使用9版本的会报错npm install vue-i18n8.27.0 --savevue3使用pnpm安装的语句pnpm add vue-i18nnext创建相关的语言包文件在src目录下新建i18n文件夹在新文件夹i18n中新建langs文件夹里边放语言文本文件.jszh.js存放所有的中文显示内容en.js存放所有的英文显示内容与langs文件夹同级创建index.js用于配置i18n并导出i18nzh.jsexport default { //中文 变量名:中文 }en.jsexport default { //英文 变量名:英文 }index.jsimport Vue from vue import VueI18n from vue-i18n //引入自定义语言配置 import zh from ./langs/zh import en from ./langs/en import fan from ./langs/fan Vue.use(VueI18n); // 全局注册国际化包 // 准备翻译的语言环境信息 const i18n new VueI18n({ locale: sessionStorage.getItem(lang) || 简, //将语言标识存入localStorage或sessionStorage中首次默认中文显示非首次则以localStorage为准 messages: { // 繁体语言包 繁: { ...fan }, // 中文语言包 简: { ...zh }, //英文语言包 ENG: { ...en } }, silentTranslationWarn: true, //解决vue-i18n黄色警告value of key xxx is not a string和cannot translate the value of keypath xxx.use the value of keypath as default,可忽略 globalInjection: true, // 全局注入 fallbackLocale: 简, // 指定的locale没有找到对应的资源或当前语种不存在时默认设置当前语种为中文 }); export default i18n在main里导入语言包文件main.jsimport i18n from ./i18n Vue.use( { i18n: (key, value) i18n.t(key, value) // 在注册Element时设置i18n的处理方法,可以实现当点击切换按钮后elementUI可以自动调用.js语言文件实现多语言切换 } ) new Vue({ render: h h(App), i18n }).$mount(#app)ts文件切换语言this.$i18n.locale ENG;//切换为英文基本使用1.在模板字符串中使用{{ $t(变量名) }} button{{ $t(submit) }}/button2.绑定属性使用:属性名$t(变量名) input typetext :placeholder$t(FromSub.content.placeholder1)/3.在script中使用this.$t(变量名)注意用这种方法在data(){}中获取的变量存在更新this.$i18n.locale的值时无法自动切换的问题需要刷新页面才能切换语言。解决方案1调整写法2写在计算属性computed:{…}中不要写在data(){return{…}}中vue3import { computed } from vue import { useI18n } from vue-i18n const { tm } useI18n() const genderOptions computed(() tm(变量名))用computed是为了切换语言时选项能跟着更新。4.变量名不固定{{ $t(msg.${msgss}) }}//msgss是一个变量语言切换会自动触发校验规则用户体验感差先监听语言切换时清除校验规则const { locale } useI18n() watch(locale, () { formRef.value?.clearValidate() })给el-form加上:validate-on-rule-changefalse避免切换语言时因rules变化而自动重新校验。