项目从vue2升级到vue3,VueI18n需要适当调整。主要是从 Vue I18n v8.x 到 Vue I18n v9 或更高版本的变化,这里初始化:
详情请参考:
Vue I18n v8.x:
import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n) const i18n = new VueI18n({ // ... }) new Vue({ i18n, // ... })
Vue I18n v9 或更高版本:
import { createApp } from 'vue' import { createI18n } from 'vue-i18n' const i18n = createI18n({ // ... }) const app = createApp({ // ... }) app.use(i18n)
原因:Vue 3 全局 API 更改,以及组件实例相关的 Vue 3 API 架构更改。
bkui-cli创建的vue2项目(magicBox组件库升级
vue2
“vue-i18n”: “^8.26.8”,
import Vue from 'vue'; import VueI18n from 'vue-i18n'; import chineseJson from '../lang/zh-cn.json'; import englishJson from '../lang/en.json'; import dayjs from 'dayjs'; import 'dayjs/locale/zh-cn'; // import locale import { getCookie } from '@/utils'; Vue.use(VueI18n); let currentLang = getCookie('blueking_language') || 'zhCN'; if (currentLang === 'en') { currentLang = 'enUS'; dayjs.locale('en'); } else { currentLang = 'zhCN'; dayjs.locale('zh-cn'); } const i18n = new VueI18n({ locale: getCookie('blueking_language') || 'zh-cn', fallbackLocale: 'zh-cn', silentTranslationWarn: true, messages: { en: { ...englishJson }, 'zh-cn': { ...chineseJson }, }, }); window.i18n = i18n; export default i18n;
vue3
“vue-i18n”: “^9.1.10”,
import { createI18n } from 'vue-i18n'; import dayjs from 'dayjs'; import 'dayjs/locale/zh-cn'; // import locale import { getCookie } from '@/utils/utils'; import chineseJson from '../lang/zh-cn.json'; import englishJson from '../lang/en.json'; let currentLang = getCookie('blueking_language') || 'zhCN'; if (currentLang === 'en') { currentLang = 'enUS'; dayjs.locale('en'); } else { currentLang = 'zhCN'; dayjs.locale('zh-cn'); } const i18n = createI18n({ locale: getCookie('blueking_language') || 'zh-cn', fallbackLocale: 'zh-cn',// 设置备用语言 silentTranslationWarn: true, globalInjection: true, messages: { en: { ...englishJson }, 'zh-cn': { ...chineseJson }, }, }); // window.i18n = i18n; export default i18n;
注意:globalInjection 为真
使用注意事项:
在vue template()和defineComponent渲染函数中直接使用this.$t没有问题。
import { defineComponent } from 'vue';
import { Exception } from 'bkui-vue';
export default defineComponent({
props: {
type: String,
msg: String,
},
render() {
return (
{this.$t('国际化示例')}
);
},
});
但是在step函数中,需要
import { defineComponent } from 'vue'; import { Exception } from 'bkui-vue'; import { useI18n } from 'vue-i18n'; export default defineComponent({ setup() { const { t } = useI18n(); return () => ({t('无业务权限')}); }, });{t('你没有相应业务的访问权限,请前往申请相关业务权限')}{t('请联系管理员添加')}
参考:
切换语言
这个和vue2一样
import { useI18n } from 'vue-i18n' const { locale } = useI18n() const changeLang = (lang: string) => { locale.value = lang localStorage.setItem('lang', lang)// getCookie('lang',lang) 刷新页面 }English中文
转载文章《vue2升级vue3:vue2 vue-i18n升级到vue3 with VueI18n v9》,
请注明出处:
© 版权声明
本站下载的源码均来自公开网络收集转发二次开发而来,
若侵犯了您的合法权益,请来信通知我们1413333033@qq.com,
我们会及时删除,给您带来的不便,我们深表歉意。
下载用户仅供学习交流,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担,访问及下载者下载默认同意本站声明的免责申明,请合理使用切勿商用。
THE END
暂无评论内容