📖 概述
Vue 3 國際化(i18n)是構建多語言應用的核心需求。本文檔介紹 Vue 3 中實現國際化的主流方案,包括 vue-i18n、Vite 插件方案和自定義解決方案。
🎯 主流方案對比
方案 | 優點 | 缺點 | 適用場景 |
---|---|---|---|
vue-i18n | 功能完整、生態成熟 | 包體積較大 | 大型應用 |
Vite 插件 | 輕量、編譯時優化 | 功能相對簡單 | 中小型應用 |
自定義方案 | 完全可控、定制化 | 開發成本高 | 特殊需求 |
🚀 方案一:vue-i18n(推薦)
安裝配置
npm install vue-i18n@next
基礎配置
// src/i18n/index.ts
import { createI18n } from "vue-i18n";const messages = {"zh-CN": {message: {hello: "你好世界",welcome: "歡迎 {name}",},},"en-US": {message: {hello: "Hello World",welcome: "Welcome {name}",},},
};const i18n = createI18n({legacy: false, // Vue 3 必須設置為 falselocale: "zh-CN",fallbackLocale: "en-US",messages,
});export default i18n;
在組件中使用
<script setup lang="ts">
import { useI18n } from "vue-i18n";const { t, locale } = useI18n();// 切換語言
const switchLanguage = (lang: string) => {locale.value = lang;
};
</script><template><div><h1>{{ t("message.hello") }}</h1><p>{{ t("message.welcome", { name: "Vue" }) }}</p><button @click="switchLanguage('en-US')">English</button><button @click="switchLanguage('zh-CN')">中文</button></div>
</template>
? 方案二:Vite 插件方案
安裝配置
npm install @intlify/unplugin-vue-i18n
Vite 配置
// vite.config.ts
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import VueI18n from "@intlify/unplugin-vue-i18n/vite";
import { resolve } from "path";export default defineConfig({plugins: [vue(),VueI18n({include: resolve(__dirname, "./src/locales/**"),}),],
});
🎨 方案三:自定義國際化方案
創建國際化工具
// src/utils/i18n.ts
import { ref, computed } from "vue";interface LocaleMessages {[key: string]: any;
}const currentLocale = ref("zh-CN");
const messages = ref<Record<string, LocaleMessages>>({});// 加載語言包
export const loadLocale = async (locale: string) => {try {const module = await import(`../locales/${locale}.json`);messages.value[locale] = module.default;currentLocale.value = locale;} catch (error) {console.error(`Failed to load locale: ${locale}`, error);}
};// 翻譯函數
export const t = (key: string, params?: Record<string, any>): string => {const keys = key.split(".");let value = messages.value[currentLocale.value];for (const k of keys) {value = value?.[k];}if (!value) return key;if (params) {return value.replace(/\{(\w+)\}/g, (_, param) => params[param] || "");}return value;
};// 組合式函數
export const useI18n = () => {const locale = computed(() => currentLocale.value);const setLocale = (newLocale: string) => {loadLocale(newLocale);};return {t,locale,setLocale,};
};
🔧 高級功能
數字格式化
// 使用 vue-i18n 的數字格式化
const { n } = useI18n();// 格式化數字
n(1234.56, "currency"); // $1,234.56
n(1234.56, { style: "currency", currency: "CNY" }); // ¥1,234.56
日期格式化
// 使用 vue-i18n 的日期格式化
const { d } = useI18n();// 格式化日期
d(new Date(), "long"); // 2024年1月15日
d(new Date(), { year: "numeric", month: "long", day: "numeric" });
復數處理
// 復數規則
const messages = {"zh-CN": {apple: "{count} 個蘋果",},"en-US": {apple: "{count} apples",},
};// 使用
t("apple", { count: 5 }); // "5 個蘋果"
📱 響應式語言切換
持久化語言設置
// src/composables/useLocale.ts
import { ref, watch } from "vue";const currentLocale = ref(localStorage.getItem("locale") || "zh-CN");watch(currentLocale, (newLocale) => {localStorage.setItem("locale", newLocale);document.documentElement.lang = newLocale;
});export const useLocale = () => {const setLocale = (locale: string) => {currentLocale.value = locale;};return {locale: currentLocale,setLocale,};
};
?? 注意事項
- 性能優化:大型應用建議使用懶加載語言包
- SEO 友好:確保服務端渲染時正確處理語言
- 回退機制:始終提供默認語言作為回退
- 文化適配:考慮不同地區的日期、數字格式差異
📝 總結
Vue 3 的國際化方案提供了強大的功能,包括多語言支持、日期格式化、復數處理等。通過使用 vue-i18n 插件,開發者可以輕松實現國際化,并確保應用在不同地區和語言環境下都能提供良好的用戶體驗。同時,通過響應式語言切換和持久化語言設置,可以進一步提升應用的靈活性和用戶體驗。
?Vue 3多語言應用開發實戰:vue-i18n深度解析與最佳實踐 - 高質量源碼分享平臺-免費下載各類網站源碼與模板及前沿技術分享