VUE3+TS+Vite uses i18n international plug-in
- Download i18n plugin
npm install vue-i18n
- Create a locals folder in the src directory, including index.ts, en.ts, zh.ts (only switch between Chinese and English)
/en.ts
export default {
login: {
login: 'login',
userName: 'userName',
password: 'password'
}
}
/zh.ts
export default {
login: {
login: '登录',
userName: '用户名',
password: '密码'
}
}
/index.ts
import {
createI18n } from "vue-i18n";
// 导入全局中英文配置对象
import zh from './zh'
import en from './en'
const messages = {
en,
zh,
}
const language = (navigator.language || 'en').toLocaleLowerCase() // 这是获取浏览器的语言
const i18n = createI18n({
legacy: false, //解决vue-i18n报错Uncaught (in promise) SyntaxError: Not available in legacy mode
locale: localStorage.getItem('lang') || language.split('-')[0] || 'en', // 首先从缓存里拿,没有的话就用浏览器语言,
fallbackLocale: 'en', // 设置备用语言
messages,
})
export default i18n
3. Finally, just introduce it in main.ts
import {
createApp } from 'vue'
import i18n from './locals'
const app = createApp(App)
app.use(i18n)
app.mount('#app')
At this time, the i18n warning message may appear in the browser's debugging box. You can vite.config.ts
add the following code to the file.
export default defineConfig({
resolve:{
alias: {
'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js', //去除vue-i18n的警告信息
}
},
})
<template>
Use in To
use a $t()
method, or you v-t
can use
<div>
{
{
`$t('login.userName')`}}
</div>
<div v-t="'login.password'"></div>
setup
used in
<script setup lang="ts">
import {
useI18n } from 'vue-i18n'
const {
t } = useI18n()
console.log(t('login.useName'))
</script>
vue-i18n provides a global variable locale, which can be modified directly
<template>
<div class="menu">
<div class="menu-item" @click="changeLang('en')">English</div>
<div class="menu-item" @click="changeLang('zh')">中文</div>
</div>
</template>
<script setup lang="ts">
import {
useI18n } from 'vue-i18n'
const {
locale } = useI18n()
const changeLang = (lang: string) => {
locale.value = lang
localStorage.setItem('lang', lang)// 重要!下面遇到问题里解释
}
</script>
end