vue3.0 + ts + element-plus + i18n 中英文切换
1、安装i18n:
npm install vue-i18n@next
2、main.ts 引入:
import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; import ElementPlus from 'element-plus'; import 'element-plus/lib/theme-chalk/index.css'; import ZhLocale from 'element-plus/lib/locale/lang/zh-cn'; // 中文 import EhLocale from 'element-plus/lib/locale/lang/en'; // 英文 import I18n from "@/lang/index"; //引入i18n组件
let locale = '';
//控制 element-plus 组件语言 if(I18n.global.fallbackLocale == 'zh') { locale = ZhLocale as unknown as string; } else { locale = EhLocale as unknown as string; } createApp(App).use(store).use(router).use(ElementPlus, { locale }).use(I18n).mount('#app');
3、src 新建 lang 文件:
index.js:
import { createI18n } from 'vue-i18n' const i18n = createI18n({ locale: localStorage.getItem('lang') || 'zh', //默认显示的语言 messages: { zh: require('./zh.js'), //引入语言文件 en: require('./en.js') } }) export default i18n;
zh.js:
module.exports = { header_menu: { login:'登录', register:'注册', logout:'退出登录', } }
en.js:
module.exports = { header_menu: { login: 'Login', register: 'Register', logout: 'Log out', } }
4、中英文切换组件:
<el-dropdown trigger="click" @command="handleSetLanguage" class="languages"> <div style="font-size: 15px;"> <span>{{langName}}</span> <i class="el-icon-arrow-down el-icon--right"/> </div> <template #dropdown> <el-dropdown-menu> <el-dropdown-item :disabled="language==='zh'" command="zh">中文</el-dropdown-item> <el-dropdown-item :disabled="language==='en'" command="en">English</el-dropdown-item> </el-dropdown-menu> </template> </el-dropdown> // setup: const langName = ref(''); const language = ref(''); // 切换事件: const handleSetLanguage = (lang: string) => { if(lang === 'zh') { langName.value = '中文'; } else { langName.value = 'English'; } language.value = lang; localStorage.setItem('lang', lang); ElMessage.success('语言切换成功'); location.reload(); };
//页面加载判断语言
onMounted(()=>{
if(localStorage.getItem('lang') == undefined || localStorage.getItem('lang') == 'zh') {
langName.value = '中文';
language.value = 'zh';
} else {
langName.value = 'English';
language.value = 'en';
}
})