vue3.2 之 i18n的使用
1:i18n简单使用
src / i18n / index.ts
import { createI18n } from 'vue-i18n'
import EN from './en'
import ZH from './zh'
const messages = {
en: {
...EN
},
zh: {
...ZH
}
}
const getCurrentLanguage = () => {
const UAlang = navigator.language
const langCode = UAlang.indexOf('zh') !== -1 ? 'zh' : 'en'
localStorage.setItem('lang', langCode)
return langCode
}
const i18n = createI18n({
legacy: false,
globalInjection: true,
locale: getCurrentLanguage() || 'zh',
messages: messages
})
export default i18n
src / i18n / en.ts
export default {
menus: {
title: 'title',
btn: 'btn'
}
}
src / i18n / zh.ts
export default {
menus: {
title: '标题',
btn: '按钮'
}
}
main.ts
import i18n from '@/i18n/index.ts'
const app = createApp(App)
app.use(i18n)
使用
<div>{{ $t('menus.title') }}</div>
<el-button type="success">我是按钮 - {{$t('menus.btn')}}</el-button>
效果
2:i18n 语音的切换
components / lang / Lang.vue
<!-- -->
<template>
<el-dropdown @command="changeLang">
<span class="el-dropdown-link">
语言切换
<el-icon class="el-icon--right">
<arrow-down />
</el-icon>
</span>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item :disabled="currentLang === 'zh'" command="zh"
>中文</el-dropdown-item
>
<el-dropdown-item :disabled="currentLang === 'en'" command="en"
>English</el-dropdown-item
>
</el-dropdown-menu>
</template>
</el-dropdown>
</template>
<script setup lang="ts" name="Lang">
import { ArrowDown } from '@element-plus/icons-vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const currentLang = computed(() => {
return i18n.locale.value
})
const changeLang = (val) => {
i18n.locale.value = val
localStorage.setItem('lang', val)
}
</script>
<style lang="scss" scoped></style>
使用 Lang组件
<template>
<div>
<div>{{ $t('menus.title') }}</div>
<el-button type="success">我是按钮 - {{ $t('menus.btn') }}</el-button>
<Lang></Lang>
</div>
</template>
<script setup lang="ts" name="Home">
import Lang from '@/components/lang/Lang.vue'
</script>
效果
|