1第一种解决办法vue-i18n
安装vue-i18n
npm install vue-i18n
新建lang文件夹
在lang下新建 en_us.ts
const en_us = {
title:{
home:'home',
about:'about'
},
week:{
Monday:'Monday',
Tuesday:'Tuesday'
}
}
export default en_us;
在lang下新建 zh_cn.ts
const zh_cn = {
title:{
home:'首页',
about:'关于'
},
week:{
Monday:'星期一',
Tuesday:'星期二'
}
}
export default zh_cn;
在lang下新建ar.ts
const ar = {
title:{
home:'منزل .',
about:'حول .'
},
week:{
Monday:'الاثنين .',
Tuesday:'يوم الثلاثاء'
}
}
export default ar;
在lang下新建 index.ts
import { createI18n } from "vue-i18n";
import zh_cn from "./zh_cn";
import en_us from "./en_us";
const i18n = createI18n({
legacy:false,
locale:'zh_cn',
messages:{
zh_cn,
en_us,
ar,
},
silentFallbackWarn:true,
missingWarn:false,
silentTranslationWarn:true,
fallbackWarn:false
})
export default i18n;
想要多种语言以此类推...
最后在main.ts挂载
//导入语言包
import i18n from './lang'
app.use(i18n)
页面语言切换
<template>
<div>
<!-- 使用 :click.native 或者定义一个方法,并将参数作为方法的参数 -->
<el-button @click="changeLanguage('zh_cn')">中文</el-button>
<el-button @click="changeLanguage('en_us')">英文</el-button>
<el-button @click="changeLanguage('ar')">阿拉伯</el-button>
</div>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { ref, onMounted,watch } from "vue";
// 获取 vue-i18n 实例的 locale 属性
const { locale } = useI18n({ useScope: "global" });
// 定义一个响应式变量来存储当前的 locale
const currentLocale = ref(localStorage.getItem("locale") || "zh_CN");
// 在组件加载时,同步 locale 到 vue-i18n 的 locale
onMounted(() => {
locale.value = currentLocale.value;
});
// 监听 currentLocale 的变化,并更新 localStorage 和 vue-i18n 的 locale
watch(currentLocale, (newVal) => {
localStorage.setItem("locale", newVal);
locale.value = newVal;
});
// 定义一个方法,用于改变当前语言
const changeLanguage = (lang: string) => {
currentLocale.value = lang;
};
</script>
<style scoped>
/* 样式 */
</style>
页面中文字展示
<template>
<div>
<h1>{{ t("week.Monday") }}</h1>
</div>
</template>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
</script>
<style scoped>
</style>