对于一些国际化的项目来说,我们就需要配置多种语言
那么,vue3如何配置国际化呢?
这里采用vue-i18n插件进行多语言配置
1.安装
yarn add vue-i18n
2.配置
在src目录下新建lang文件夹,用于存放语言配置
index.ts
import en from './en' // 英文语言配置
import zhCN from './zh-CN' // 中文语言配置
import { createI18n } from 'vue-i18n'
const config = localStorage.getItem('config') // 当前使用的语言类型
let lang = 'zhCN'
if (config) {
lang = JSON.parse(config).lang || 'zhCN'
}
export const i18n = createI18n({
legacy: false, // componsition API需要设置为false
locale: lang,
globalInjection: true, // 可以在template模板中使用$t
messages: {
en,
zhCN
}
})
en.ts
export default {
message: 'Hello',
say: 'Hello {name}'
}
zh-CN
export default {
message: '您好',
say: '您好 {name}'
}
3.挂载
在main.ts中挂载
import { i18n } from '@/lang/index'
const app = createApp(App)
app.use(i18n).mount('#app')
此时使用会出现如下警告
vue-i18n.esm-bundler.js:39 You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
所以,需要在配置文件中对vue-i18n做别名设置 vite.config.ts
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js'
}
},
4.使用
在vue的template文件中可以直接使用$t('message') 例如:
<template>
<div>{{ $t('message')}}</div>
<div>{{ $t('say', { name: 'Lisa'})}}</div>
</template>
在vue文件的的script中使用
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
const sayHello = t('say', { name: 'Lisa'})
</script>
在ts文件中使用 .index.ts
// 需要从设置的lang/index中获取配置的i18n
import { i18n } from '@/lang/index'
const { t } = i18n.global
const sayHello = t('say', { name: 'Lisa'})
5.动态更改配置语言
如果需要动态配置语言,在更改完成以后,需要重新更新当前页面,因为ts文件中引入的语言配置必须在页面重新加载后才可以正常显示更改后的语言
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
const changeLang = (val: string) => {
locale.value = val
localStore.setItem('config', { lang: val })
location.reload()
}
</script>