添加国际化库 Vue I18n
环境准备
拉取项目
# 从 GitHub 拉取项目(存在网络限制)
$ git clone --branch v0.0.3 https://github.com/geenln/vue3-elemnt-plus-ts.git
# 或者从 Gitee 拉取项目
$ git clone --branch v0.0.3 https://gitee.com/genin/vue3-elemnt-plus-ts.git
安装项目依赖
$ npm install
启动开发服务器
$ npm run dev
添加国际化库 Vue I18n
安装 Vue I18n
$ npm install vue-i18n
创建文件 src/i18n/lang/en.json,src/i18n/lang/zh.json
src/i18n/lang/en.json
{
"message": "English"
}
src/i18n/lang/zh.json
{
"message": "中文"
}
创建文件 src/i18n/index.ts
src/i18n/index.ts
import { createI18n } from 'vue-i18n'
import en from '@/i18n/lang/en.json'
import zh from '@/i18n/lang/zh.json'
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en,
zh
}
})
export default i18n
更新文件 src/main.ts
src/main.ts
import {createApp} from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import pinia from './store'
+import i18n from './i18n'
const app = createApp(App)
app.use(router)
app.use(pinia)
+app.use(i18n)
app.mount('#app')
Vue I18n 国际化示例
更新文件 src/App.vue
src/App.vue
<script setup lang="ts">
import {useCounterStore} from '@/store/modules/counter'
+import {useI18n} from 'vue-i18n'
const counterStore = useCounterStore()
+const {t, locale} = useI18n()
</script>
<template>
<h1>Vue3 Element Plus Ts</h1>
+ <button
+ class="border p-2 rounded-md"
+ @click="locale = locale !== 'zh' ? 'zh' : 'en'"
+ >
+ 切换语言 {{ locale }}
+ </button>
+ <div>
+ {{ t('message') }}
+ </div>
<button class="border p-2 rounded-md" @click="counterStore.increment()">
count加1
</button>
<div class="flex gap-2">
<span>{{ counterStore.count }}</span>
<span>{{ counterStore.doubleCount }}</span>
</div>
<div class="flex gap-2">
<RouterLink to="/t1" class="underline text-teal-600">TestA.vue</RouterLink>
|
<RouterLink to="/t2" class="underline text-teal-600">TestB.vue</RouterLink>
</div>
<RouterView />
</template>
添加 i18n Ally 国际化插件
更新文件 .vscode/settings.json
.vscode/settings.json
{
"editor.fontSize": 18,
"files.autoSave": "afterDelay",
"files.eol": "\n",
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.quickSuggestions": {
"strings": "on"
},
+ "i18n-ally.localesPaths": ["src/i18n/lang"]
}
打开 i18n Ally 国际化插件图标可以看到翻译情况