vue3
应用的国际化库为:i18n
装置形式:
npm install vue-i18n@next
装置实现后在src
文件夹下新建lang
文件夹
在lang
文件夹下新建须要语言转换的文件夹,这里以中文zh
和英文en
举例,在这两个文件夹下新建须要转换的语言
在zh
的index.ts
中写好咱们须要转换的语言en
的index.ts
也是一样的
在lang
文件夹下新建index.ts
文件,在该文件下引入方才的建设的语言包,配置须要应用的默认语言
// lang -> index.tsimport { createI18n } from 'vue-i18n'import zh from './zh' import en from './en'/* 这里必须是messages名称 */const messages = { 'zh-US' : zh, 'en-US' : en}const i18n = createI18n({ legacy: false, // 应用 Composition API 模式,则须要将其设置为false globalInjection: true, //全局失效$t locale: 'zh-US', // 默认应用的语言 messages, // 应用数据源})export { i18n }
在main.ts
文件下导入并挂载i18n
import { createApp } from "vue";import "./style.css";import App from "./App.vue";import router from "./router/index";// 引入国际化import { i18n } from './lang/index'const app = createApp(App)/* globalProperties一个用于注册可能被利用内所有组件实例拜访到的全局属性的对象。 */app.config.globalProperties.$i18n = i18n; app.use(router).use(i18n) // 挂载i18n.mount("#app")
main
文件设置好后,咱们就能够在页面应用了,页面的应用办法:
<div> <el-switch v-model="lang" inline-prompt style="--el-switch-on-color: #13ce66; --el-switch-off-color: #97a0ff" active-text="中" inactive-text="英" @change="languageChange" /> <!-- 在页面中应用,这里对应的是语言包中的对象,此处能够应用模板字符串 --> <span>{{ t('navUtil.loginText') }}</span></div>
import { useI18n } from "vue-i18n";const { t } = useI18n();const lang = ref(true); // 开关,语言状态切换/* getCurrentInstance()能够用来获取以后组件实例 */let current = getCurrentInstance()?.appContext.config.globalProperties as any;// 依据状态,切换国际化const languageChange = (val : boolean) => { // false英 true中,此处的zh-US就是lang -> index.ts -> messages对象的键名 val ? current.$i18n.locale = 'zh-US' : current.$i18n.locale = 'en-US'}
如果是后盾返回的菜单数据,咱们须要依据菜单数据的键做语言解决,例如这样的
首先须要在lang
对应的中英文文件夹下新增语言配置,因为后盾返回的键名都是一样的,咱们能够应用 键+id
的办法让这些键放弃独立,例如:
菜单个别都是遍历进去的,在页面中用模板字符串拼接id即可
<span>{{ t(`menu.authName${item.id}`) }}</span>
如果感觉这篇文章对你有帮忙,欢送点赞、珍藏、转发✨哦~