同时实现UI组件库(这里以ElementPlus为例)和内容文字的中英文切换
1. 安装vueI18n和element-plus
pnpm i vue-i18n element-plus
2. 然后在项目中src目录下新建lang文件夹,里面新建en.ts和zh.ts还有index.ts
index.ts
import { createI18n } from 'vue-i18n'
import en from './en'
import zh from './zh'
import type { App } from 'vue'const messages = { en, zh }const localeData = {globalInjection: true, // 如果设置true, $t() 函数将注册到全局legacy: false, // 如果想在composition api中使用需要设置为falselocale: localStorage.getItem('lang') || 'zh', // 当前选择的语言messages, // set locale messages
}export const i18n = createI18n(localeData)export const setupI18n = {install(app: App) {app.use(i18n)},
}
en.ts
export default {router: {Dashboard: 'homePage',},
}
zh.ts
export default {router: {Dashboard: '首页',},
}
3. 在mian.ts中进行注册使用
// ElementPlus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// vuei18n
import { setupI18n } from '@/lang'
const app = createApp(App)
app.use(ElementPlus)
app.use(setupI18n)
4. 在pinia中新增处理语言的逻辑
config.ts
import { defineStore } from 'pinia'
import { i18n } from '@/lang'
import { ref } from 'vue'export const useConfigStore = defineStore('config', () => {// 当前语言let language = ref(localStorage.getItem('lang') || 'zh')// 设置语言const setLanguage = (lang: string) => {const { locale }: any = i18n.globallanguage.value = langlocale.value = lang}return {language,setLanguage,}
})
index.ts
import { useConfigStore } from './config'export { useConfigStore }
5. 修改App.vue文件
<template><el-config-provider :locale="lang[language]"><RouterView /></el-config-provider>
</template><script setup lang="ts">
import { computed } from 'vue'
import { ElConfigProvider } from 'element-plus'
import { RouterView } from 'vue-router'
import { useConfigStore } from './stores'
import zh from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'const configStore = useConfigStore()const language = computed(() => configStore.language)const lang: any = { zh, en }
</script>
此时就完成了中英文切换的功能,我们进行测试一下
- 点击按钮,传入相应的语言即可。
<template><el-button @click="changeLanguage('zh')">中文</el-button><el-button @click="changeLanguage('en')">英文</el-button><el-paginationv-model:current-page="currentPage4"v-model:page-size="pageSize4":page-sizes="[100, 200, 300, 400]":small="small":disabled="disabled":background="background"layout="total, sizes, prev, pager, next, jumper":total="400"/>{{ $t('router.Dashboard') }}
</template><script lang="ts" setup>
import { ref } from 'vue'
import { useConfigStore } from '@/stores'const configStore = useConfigStore()const currentPage4 = ref(4)
const pageSize4 = ref(100)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)const changeLanguage = (language: 'zh' | 'en') => {configStore.setLanguage(language)
}
</script>
测试结果: