【vue3】:国际化解决方案
element plus非 element plus下载根据不同 locale 使用加载不同的语言文件,element plus 无需手动加载,只需设置 或者 即可语言文件i18n实例对象全局注册 i18n对象在中使用在中使用在中使用
·
# 国际化
-
element plus
-
非 element plus
# 常规操作
下载 vue-i18n
# element plus 国际化
<template>
<el-config-provider :locale="$store.getters.language === 'en' ? en : zhCn">
<router-view></router-view>
</el-config-provider>
</template>
根据不同 locale 使用<el-config-provider>加载不同的语言文件,element plus 无需手动加载,只需设置 en或者 zhCn即可
# 非 element plus 国际化
- 创建语言文件
- 创建 i18n实例对象
- 全局注册 i18n对象
语言文件
// i18n/lang/en.js
export default {
login: {
title: 'User Login',
loginBtn: 'Login',
usernameRule: 'Username is required',
passwordRule: 'Password cannot be less than 6 digits'
}
}
// i18n/lang/zh.js
export default {
login: {
title: '用户登录',
loginBtn: '登录',
usernameRule: '用户名为必填项',
passwordRule: '密码不能少于6位'
}
}
i18n实例对象
// i18n/index.js
import { createI18n } from 'vue-i18n'
import zhLocale from './lang/zh'
import enLocale from './lang/en'
import store from '@/store'
const messages = {
en: {
msg: {
...enLocale
}
},
zh: {
msg: {
...zhLocale
}
}
}
function getLanguage () {
return store && store.getters && store.getters.language
}
const i18n = createI18n({
// 使用 Composition API 模式,则需要将其设置为 false
legacy: false,
// 全局注入 $t 函数
globalInjection: true,
locale: getLanguage(),
messages
})
export default i18n
全局注册 i18n对象
// main.js
import i18n from '@/i18n'
app.use(store).use(router).use(i18n).mount('#app')
在vue页面<template>中使用
<h3 class="title">{{ $t('msg.login.title') }}</h3>
在 vue页面javascript中使用
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const message = ref();
message.value = i18n.t('msg.login.usernameRule')
console.log(message);
在js文件中使用
import i18n from '@/i18n';
console.log(i18n.global.t('msg.login.passwordRule'));
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)