ant-design-vue中英文切换
一 效果
二 依赖
npm install ant-design-vue@4.x --save
npm install vue-i18n@next
三 代码
1 main.ts引入
2 app.vue文件
<template>
<ConfigProvider :locale="antdLocale">
<div id="app">
<RouterView />
</div>
</ConfigProvider>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ConfigProvider } from 'ant-design-vue'
import { RouterView } from 'vue-router'
const { locale } = useI18n()
// 使用 ref 创建一个新的响应式变量来存储 ant-design-vue 的 locale
const antdLocale = ref()
// 监听语言变化
watch(
() => locale.value,
(newLocale) => {
if (newLocale === 'zh') {
// 引入中文语言包
import('ant-design-vue/es/locale/zh_CN').then(({ default: zhCN }) => {
antdLocale.value = zhCN
})
} else {
// 引入英文语言包
import('ant-design-vue/es/locale/en_US').then(({ default: enUS }) => {
antdLocale.value = enUS
})
}
},
{
immediate: true,
},
)
</script>
3. locales
3.1 index.ts
import { createI18n } from 'vue-i18n'
import en from './en'
import zh from './zh'
import 'dayjs/locale/zh-cn'
import 'dayjs/locale/en'
import enUS from 'ant-design-vue/es/locale/en_US'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
const messages = {
en: {
...en,
...enUS,
},
zh: {
...zh,
...zhCN,
},
}
const langLocale = localStorage.getItem('lang') || 'en'
const i18n = createI18n({
locale: langLocale, // 默认语言
fallbackLocale: 'en', // 备用语言
messages,
})
export default i18n
en.ts
zh.ts
/en/indexPage.ts
/zh/indexPage.ts
四 切换
<template>
<div class="HeaderLayout">
<div class="HeaderLayout-left">
{{ $t('indexPage.name') }}
</div>
<div class="HeaderLayout-right">
<div class="HeaderLayout-right-locale">
<div
class="HeaderLayout-right-locale-item"
v-for="(item, index) in languageList"
:class="{ selectLanguage: defaultLanguage == item.value }"
:key="index"
@click="onClickLocale(item.value)"
>
{{ item.value }}
</div>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { locale } = useI18n({
useScope: 'global',
})
const defaultLanguage = ref(localStorage.getItem('lang') || 'en')
const languageList = ref([
{
label: '中文',
value: 'zh',
},
{
label: '英文',
value: 'en',
},
])
const onClickLocale = (str: string) => {
defaultLanguage.value = str
locale.value = str
}
</script>
<style lang="less" scoped>
.HeaderLayout {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
&-left {
font-size: 16px;
font-weight: 700;
color: #000;
}
&-right {
display: flex;
align-items: center;
&-locale {
width: 108px;
height: 36px;
display: flex;
align-items: center;
border: 1px solid rgba(#000, 0.1);
border-radius: 4px;
box-sizing: border-box;
margin-left: 16px;
&-item {
width: 54px;
height: 34px;
font-weight: 600;
font-size: 14px;
color: rgba(#000, 0.7);
text-align: center;
line-height: 32px;
border-radius: 4px;
cursor: pointer;
&.selectLanguage {
color: #fff;
background: rgba(gray, 0.5);
}
}
}
}
}
</style>