1.安装依赖
pnpm install vue-i18n
2.创建国际化配置文件
在 src
目录下创建一个 locales
文件夹,并在其中创建不同语言的翻译文件,例如 en.json
和 zh.json
。
{
"demo": {
"hello": "hello"
}
}
{
"demo": {
"hello": "你好"
}
}
3.配置 Vue I18n
在 src
目录下创建一个plugins
文件夹,并在其中创建 i18n.ts
文件,并在其中配置 Vue I18n。
import { createI18n } from 'vue-i18n'
// 导入翻译文件
import en from '@/locales/en.json'
import zh from '@/locales/zh.json'
// 创建 Vue I18n 实例
const i18n = createI18n({
legacy: false, // 使用 composition 模式
locale: 'zh', // 设置默认语言
fallbackLocale: 'en', // 设置回退语言
globalInjection: true, // 允许全局注入
messages: {
en,
zh
}
})
export default i18n
4.在主文件中引入 Vue I18n
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import i18n from '@/plugins/i18n'
const app = createApp(App)
app.use(i18n)
app.mount('#app')
5.使用i18n-ally插件
①下载插件i18n-ally
②配置.vscode -> settings.json
{
"i18n-ally.localesPaths": ["src/locales"],
"i18n-ally.displayLanguage": "zh",
"i18n-ally.namespace": true,
"i18n-ally.pathMatcher": "{locale}.json",
"i18n-ally.keystyle": "nested",
"i18n-ally.sourceLanguage": "zh" //locale对应国际化语言
}
6.在组件中使用 Vue I18n
<template>
<div>
<p>你好</p>
<button @click="changeLanguage('en')">英文</button>
<button @click="changeLanguage('zh')">中文</button>
</div>
</template>
<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { locale } = useI18n();
const changeLanguage = (lang: string) => {
locale.value = lang;
};
</script>
点击新路径
中文配置完成,可以在框选处编辑英文部分,或者在en.json
和 zh.json
编辑改写