npm install vue-i18n@nex
在 src 目录下新建 lang 文件夹,再创建3个ts文件,lang / index.ts , lang / en.ts , lang / zh.ts
index.ts
// index.ts
import { createI18n } from 'vue-i18n'
import zh from './zh'
import en from './en'
const messages = {
en,
zh,
}
console.log('localStorage.getItem', localStorage.getItem('language'));
const language = (navigator.language || 'en').toLocaleLowerCase() // 获取浏览器的语言
console.log('language.split', language.split('-')[0]);
const i18n = createI18n({
locale: localStorage.getItem('language') || language.split('-')[0] || 'en', // 先从缓存里拿,没有的话就用浏览器语言,
fallbackLocale: 'zh', // 设置备用语言
messages,
legacy: false,
globalInjection:true,
})
export default i18n
en.ts
export default {
login: {
login: 'login',
userName: 'userName',
password: 'password',
},
captcha: 'Captcha',
forgetPassword: 'Forget Password?',
loginTip: 'The login result is random. Just fill in the captcha',
editpassword: 'Edit Password',
logout: 'Logout',
errMsg: {
inputRequired: 'Please Input {cont}',
selectRequired: 'Please Select {cont}',
},
}
zh.ts
export default {
login: {
login: '登录',
userName: '用户名',
password: '密码',
},
captcha: '验证码',
forgetPassword: '忘记密码了?',
loginTip: '当前登录结果随机。验证码随便填',
editpassword: '修改密码',
logout: '退出登录',
errMsg: {
inputRequired: '请输入{cont}',
selectRequired: '请选择{cont}',
},
}
main.ts
import i18n from './lang/index'
app.use(i18n)
<div>
{{ $t('login.userName') }}
</div>
<div v-t="'login.password'"></div>
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
console.log(t('login.useName'))
</script>
这边我是在stores下创建了一个langConversion.ts文件。src\stores\modules\langConversion.ts
langConversion.ts
export enum LangOption {
EN = 'en',
ZH = 'zh'
}
// 语言可选项
export const langOptions = [
{ label: "English", value: LangOption.EN},
{ label: "中文", value: LangOption.ZH},
]
export async function langConversionEvent(lang:string){
// let langs = localStorage.getItem('language') === 'en'?'zh':'en'
localStorage.setItem("language", lang);
window.location.reload();
}
需要调用该方法的vue页面,这里用的NaiveUI组件
<n-select size="small" style="width: 120px;" v-model:value="optionsValue" :options="options" @update:value="handleUpdateValue"/>
<script lang="ts">
import { langConversionEvent, langOptions } from "@/stores/modules/langConversion"
export default defineComponent({
setup(){
const optionsValue = ref(localStorage.getItem('language') || language.split('-')[0])
return{
optionsValue,
options:langOptions,
handleUpdateValue (value: string) {
langConversionEvent(value)
},
}
}
})
<script>
官网:I18n