feat(i18n): 添加中文和英文语言文件,集成国际化支持
This commit is contained in:
8
src/locales/en.json
Normal file
8
src/locales/en.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"welcome": "Welcome",
|
||||
"hello": "Hello, {name}!",
|
||||
"nav": {
|
||||
"home": "Home",
|
||||
"about": "About"
|
||||
}
|
||||
}
|
8
src/locales/zh.json
Normal file
8
src/locales/zh.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"welcome": "欢迎",
|
||||
"hello": "你好,{name}!",
|
||||
"nav": {
|
||||
"home": "首页",
|
||||
"about": "关于"
|
||||
}
|
||||
}
|
24
src/main.ts
24
src/main.ts
@ -9,6 +9,12 @@ import { createI18n } from 'vue-i18n';
|
||||
import { DataLoaderPlugin } from 'unplugin-vue-router/data-loaders';
|
||||
import App from './App.vue';
|
||||
import { router } from './router';
|
||||
// 自动导入语言文件
|
||||
const messages = Object.fromEntries(
|
||||
Object.entries(import.meta.glob('./locales/*.json', { eager: true })).map(([key, value]) => {
|
||||
return [key.slice('./locales/'.length, -5), value.default];
|
||||
}),
|
||||
);
|
||||
|
||||
async function init() {
|
||||
if (import.meta.env.MODE === 'development' || 1 === 1) {
|
||||
@ -33,20 +39,10 @@ async function init() {
|
||||
.use(router)
|
||||
.use(
|
||||
createI18n({
|
||||
locale: 'zh_CN', // 默认显示语言
|
||||
fallbackLocale: 'zh_CN',
|
||||
messages: {
|
||||
en_US: {
|
||||
message: {
|
||||
hello: 'hello',
|
||||
},
|
||||
},
|
||||
zh_CN: {
|
||||
message: {
|
||||
hello: '你好',
|
||||
},
|
||||
},
|
||||
},
|
||||
legacy: false, // 使用 Composition API 模式
|
||||
locale: 'zh', // 默认语言
|
||||
fallbackLocale: 'en', // 回退语言
|
||||
messages,
|
||||
}),
|
||||
);
|
||||
app.config.globalProperties.$__DEV__ = $__DEV__;
|
||||
|
@ -19,11 +19,6 @@ import { useI18n } from 'vue-i18n';
|
||||
|
||||
const { locale } = useI18n();
|
||||
|
||||
const handleLanguageChange = (event: Event) => {
|
||||
const select = event.target as HTMLSelectElement;
|
||||
locale.value = select.value;
|
||||
};
|
||||
|
||||
// https://cn.vuejs.org/guide/extras/render-function#typing-functional-components
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const FComponent: FunctionalComponent<{ prop: string }> = (props, context) => (
|
||||
@ -46,11 +41,12 @@ const FComponent: FunctionalComponent<{ prop: string }> = (props, context) => (
|
||||
</ul>
|
||||
|
||||
<div b="1px solid pink" mt-8>
|
||||
<select :value="locale" @change="handleLanguageChange">
|
||||
<option value="zh_CN">中文</option>
|
||||
<option value="en_US">English</option>
|
||||
<select v-model="locale">
|
||||
<option value="zh">中文</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
<h1>{{ $t('message.hello') }}</h1>
|
||||
<h1>{{ $t('welcome') }}</h1>
|
||||
<p>{{ $t('hello', { name: 'John' }) }}</p>
|
||||
</div>
|
||||
|
||||
<FComponent prop="Hello World" style="margin-top: 8px"></FComponent>
|
||||
|
Reference in New Issue
Block a user