安裝依賴
yarn add element-plus vue-i18n
1. i18n是否可以有同名鍵欧瘪?
是可以的眷射,但是同名鍵會被后加載的內(nèi)容覆蓋。
在 Vue I18n 中,多個(gè)語言文件合并時(shí)妖碉,相同的鍵名會按照最后合并的語言文件的值覆蓋之前的值涌庭。例如:
const messages = {
en: {
key1: 'Value from file 1',
},
en: {
key1: 'Value from file 2', // 這個(gè)會覆蓋前一個(gè)文件的 key1
},
};
解決方法:
盡量避免同名鍵的沖突。
使用命名空間(如頁面或組件名)來區(qū)分嗅绸。
2. 拆分國際化配置文件
目錄結(jié)構(gòu)示例
src/
├── locales/
│ ├── en/
│ │ ├── home.ts
│ │ ├── about.ts
│ ├── ja/
│ │ ├── home.ts
│ │ ├── about.ts
│ ├── index.ts
各頁面的語言文件
- locales/en/home.ts
export default {
home: {
welcome: 'Welcome to the home page',
},
};
- locales/ja/home.ts
export default {
home: {
welcome: 'ホームページへようこそ',
},
};
- locales/en/common.ts
export default {
common: {
changeLanguage: 'Change Language',
},
};
- locales/ja/common.ts
export default {
common: {
changeLanguage: '言語を変更する',
},
};
- 合并語言文件
在 locales/index.ts 中合并拆分的語言文件:
import enHome from './en/home';
import enCommon from './en/common';
import jaHome from './ja/home';
import jaCommon from './ja/common';
const en = {
...enHome,
...enCommon,
};
const ja = {
...jaHome,
...jaCommon,
};
export const messages = {
en,
ja,
};
3. 配置 i18n
在 i18n.ts 中引入合并后的語言文件:
import { createI18n } from 'vue-i18n';
import { messages } from './locales';
const i18n = createI18n({
locale: 'en', // 默認(rèn)語言
fallbackLocale: 'en', // 備用語言
messages,
});
export default i18n;
4. 使用命名空間解決同名沖突
如果不同頁面使用了相同的鍵名脾猛,建議將每個(gè)頁面的配置放在命名空間下撕彤。比如在 home.ts 文件中:
export default {
home: {
welcome: 'Welcome to the home page',
},
};
在 home.ts 文件中:
export default {
home: {
welcome: 'Welcome to the about page',
},
};
使用時(shí)需要明確路徑:
<p>{{ $t('home.welcome') }}</p>
<p>{{ $t('about.welcome') }}</p>
- 測試效果
在頁面組件中使用:
<template>
<div>
<p>{{ $t('home.welcome') }}</p>
<p>{{ $t('common.changeLanguage') }}</p>
</div>
</template>
切換語言:
通過 i18n.global.locale 動態(tài)切換:
在@/locales/index.ts中聲明
export const switchLanguage = (locale: 'en' | 'ja') => {
i18n.global.locale = locale
}
<div class="switch">
<button @click="switchLanguage('en')">English</button>
<button @click="switchLanguage('ja')">日語</button>
</div>
// 動態(tài)更新語言包
function updateLocaleMessages(locale: string, newMessages: Record<string, any>) {
const currentMessages = i18n.global.getLocaleMessage(locale);
i18n.global.setLocaleMessage(locale, {
...currentMessages,
...newMessages, // 合并新內(nèi)容
});
}
// 使用時(shí)調(diào)用
updateLocaleMessages('ja', { message: { goodbye: 'さようなら鱼鸠!' } });