第一步,安装vue-i18n(我这里版本是9.2.2)
npm install vue-i18n element-plus --save
第二步,src文件夹下创建language文件夹,目录如下
第三步,定义本地中文英文
en.ts
// en.ts
export default {
message: {
analyse: 'analyse',
data: 'data',
projectManagement: 'Project Management',
systemSetup: 'system setup'
}
}
zh.ts
export default {
message: {
analyse: '分析',
data: '数据',
projectManagement: '项目管理',
systemSetup: '系统设置'
}
}
i18n.ts
import { createI18n } from 'vue-i18n'
import zh from './zh'
import en from './en'
const i18n = createI18n({
legacy: false,
locale: 'zh',
messages: {
zh,
en
}
})
export default i18n
第四步,main.ts中引入使用
// 国际化
import i18n from './language/i18n'
app.use(i18n)
第五步,pinia状态管理
src文件夹下创建store文件(状态管理)
store下创建index.ts文件
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import zh from "element-plus/lib/locale/lang/zh-cn";
import en from "element-plus/lib/locale/lang/en";
import i18n from '@/language/i18n'
export const useCounterStore = defineStore('counter', () => {
// 变量
const count = ref(zh)
// 计算属性
const doubleLang = computed(() => {
if (localStorage.getItem('language')) {
if (localStorage.getItem('language') === 'en') {
i18n.global.locale.value = 'en'
return en
} else {
i18n.global.locale.value = 'zh'
return zh
}
}
})
// 方法action
function incrementLang(data: string) {
console.log(data, i18n)
if (data === 'zh') {
lang.value = zh
i18n.global.locale.value = data
localStorage.setItem('language', data)
} else if (data === 'en') {
lang.value = en
i18n.global.locale.value = data
localStorage.setItem('language', data)
}
}
return { count, increment, doubleCount }
})
export default useCounterStore
第六步,设置全局
在项目app.vue文件中,引入el-config-provider(详情参考element plus)
<script setup lang="ts">
import { useCounterStore } from '@/store/index'
const storea = useCounterStore()
const locale = storea.doubleLang;
console.log(locale);
</script>
<template>
<el-config-provider :locale="locale">
<router-view></router-view>
</el-config-provider>
</template>
<style scoped>
第七步,使用国际化(这边以项目头部为例,国际化语言切换也在头部)
<script setup lang="ts">
import { ref } from 'vue'
// pinia管理语言
import { useCounterStore } from '@/store/index'
const storea = useCounterStore()
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const langVa = ref('zh')
langVa.value = localStorage.getItem('language') || 'zh'
//设置语言
const handleCommand = (command: string | number | object) => {
langVa.value = command as string
storea.increment(command as string)
}
</script>
<template>
<div>
<!-- 使用方式 -->
<div>{{ t('message.data') }}</div>
<div>
<el-dropdown szie="medium" v-model="langVa" @command="handleCommand">
<svg-icon name="test" style="font-size: 18px; margin-top: 5px" />
<template #dropdown>
<el-dropdown-item command="zh" v-if="langVa !== 'zh'">简体中文</el-dropdown-item>
<el-dropdown-item command="en" v-if="langVa !== 'en'">English</el-dropdown-item>
</template>
</el-dropdown>
</div>
</div>
</template>