Internationalization Documentation - Multi-language Support and Configuration
Overview
This document details the internationalization (i18n) support mechanism of the VJSP Vue3 framework, including multi-language configuration, language switching, translation file management, and practical applications in development.
Internationalization Architecture
Core Features
- Modular Translation Management: Organize translation files in a modular way for easy maintenance and expansion
- Dynamic Language Switching: Support runtime dynamic language switching without page refresh
- Element Plus Integration: Deep integration with Element Plus component library to ensure UI component multi-language consistency
- Type Safety: Provide type-safe translation function calls
- Persistent Storage: Automatically save language preferences to local storage
Technology Stack
- Vue I18n v11: Core internationalization library
- Element Plus Internationalization: UI component library multi-language support
- Pinia State Management: Language state persistence
- Dynamic Import: On-demand loading of language packs for performance optimization
Configuration Mechanism
Language Configuration
The project supports three language environments:
- Simplified Chinese (zh-CN): Default language
- English (en): Internationalization support
- Japanese (ja): Multi-language extension
Language Pack Mapping
Element Plus language pack mapping with project language configuration:
zh-CN→ Element Pluszh-cnen→ Element Plusenja→ Element Plusja
Storage Configuration
Language settings use localStorage for persistent storage with the key name lang, ensuring user preferences remain consistent across different sessions.
Implementation Mechanism
Initialization Process
- Application Startup: Read user language preferences from localStorage
- Plugin Initialization: Configure Vue I18n instance
- Language Pack Loading: Dynamically import corresponding language translation files
- Element Plus Configuration: Set UI component library language pack
- Global Registration: Register translation functions as global properties
Language Switching Mechanism
- State Update: Update language state in Pinia store
- DOM Update: Set HTML page's
langattribute - Event Notification: Trigger global language change event
- Component Response: Related components automatically respond to language changes
Translation File Loading
Use dynamic import method to load translation files, achieving on-demand loading and code splitting:
- Basic translation files (common module)
- System module translation files (system module)
- Business module translation files (loaded on demand)
Translation File Structure
Modular Organization
Translation files are organized by functional modules, each containing independent translation resources:
src/locales/
├── common/ # Common translations
│ ├── zh-CN.ts # Chinese common translations
│ ├── en.ts # English common translations
│ └── ja.ts # Japanese common translations
├── system/ # System module translations
│ ├── zh-CN.ts # Chinese system translations
│ ├── en.ts # English system translations
│ └── ja.ts # Japanese system translations
└── module/ # Business module translationsNamespace Convention
- common: Basic translations for common operations, forms, validation, etc.
- system: Translations for system management related modules
- Business module name: Translation resources for specific business functions
Development Guide
Using Translations in Components
Composition API Usage
Use useI18n hook to get translation functions:
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
// Basic translation usage
const title = t('common.add')
// Translation with namespace
const userTitle = t('system.user.pageTitle')Options API Usage
Access translation functions through global properties:
export default {
computed: {
title() {
return this.$t('common.add')
},
},
}Business Module Development Example (Product Module)
1. Create Translation Files
Create language files in src/locales/module/product/ directory:
zh-CN.ts
export default {
product: {
pageTitle: '产品管理',
productName: '产品名称',
productCode: '产品编码',
price: '价格',
status: '状态',
addProduct: '新增产品',
editProduct: '编辑产品',
deleteProduct: '删除产品',
deleteConfirm: '确认删除产品"{name}"吗?',
addSuccess: '产品新增成功',
updateSuccess: '产品更新成功',
deleteSuccess: '产品删除成功',
},
}en.ts
export default {
product: {
pageTitle: 'Product Management',
productName: 'Product Name',
productCode: 'Product Code',
price: 'Price',
status: 'Status',
addProduct: 'Add Product',
editProduct: 'Edit Product',
deleteProduct: 'Delete Product',
deleteConfirm: 'Confirm delete product "{name}"?',
addSuccess: 'Product added successfully',
updateSuccess: 'Product updated successfully',
deleteSuccess: 'Product deleted successfully',
},
}2. Register Module Translation
Add module name in src/plugins/vueI18n/index.ts:
const otherModules: string[] = ['product']3. Usage in Components
<template>
<div>
<h2>{{ t('product.pageTitle') }}</h2>
<el-button @click="handleAdd">
{{ t('product.addProduct') }}
</el-button>
</div>
</template>
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
const handleAdd = () => {
// Product addition logic
}
</script>Language Switching Function
Function View Description
The project provides an intuitive language switching interface where users can quickly switch application languages through the language selector in the top navigation bar. The language selector uses a dropdown menu format, displaying the current language name and providing options for all supported languages.
Tool Class File Paths
Language switching function involves the following core files:
- State Management:
src/stores/modules/locale.ts- Language state and configuration management - Utility Functions:
src/utils/i18n.ts- Provides language switching and query functions - Plugin Configuration:
src/plugins/vueI18n/index.ts- Core implementation of internationalization plugin - Component Integration:
src/layout/components/Navbar.vue- Language selector component location
Switching Mechanism
Language switching uses an event-driven mechanism. When a user selects a new language:
- State Update: Update global language state through Pinia store
- DOM Synchronization: Automatically update HTML page's
langattribute - Component Response: Trigger global language change event, all components using translations automatically re-render
- Persistent Storage: User language preferences are automatically saved to local storage, ensuring consistency on next visit
The switching process requires no page refresh, providing a smooth user experience while ensuring Element Plus component library language packs are synchronized.
Best Practices
Translation Key Naming Convention
- Module Prefix: Use module name as namespace prefix
- Semantic Naming: Key names should clearly express their meaning
- Consistency: Use the same translation key for text with the same meaning
Dynamic Parameter Handling
Use Vue I18n's parameter interpolation function:
// Translation file
deleteConfirm: 'Confirm delete "{name}"?'
// Usage in component
const message = t('product.deleteConfirm', { name: productName })Plural Form Handling
For text that needs to handle plural forms:
// Translation file
itemCount: '{count} item | {count} items'
// Usage in component
const message = t('common.itemCount', { count: itemCount }, itemCount)Error Handling
- Key Not Found Handling: Provide default fallback text
- Load Failure Handling: Graceful degradation to default language
- Type Safety: Use TypeScript to ensure translation key correctness
Performance Optimization
Caching Strategy
- Local storage of user language preferences: Persist user-selected language settings through localStorage
- Avoid duplicate settings: Check current language state during language switching to avoid unnecessary update operations
Build Optimization
- Compress translation files: Automatically compress resource files during Vite build
- Chunking strategy: Optimize loading performance through vendor chunking
Troubleshooting
Common Issues
- Translation Key Not Found: Check key name spelling and namespace
- Language Switching Invalid: Confirm language pack loaded successfully
- Element Plus Language Mismatch: Check language pack mapping configuration
Debugging Tips
- Use Vue Devtools to check translation state
- Check language pack loading logs in browser console
- Verify language settings in localStorage
Extension Guide
Adding New Languages
- Create corresponding language directory under
src/locales/ - Add language pack mapping configuration
- Update language selector support
- Test new language functionality
Custom Translation Loader
Implement custom translation loading logic by modifying the loadModuleMessages function, supporting loading translation resources from remote servers or CDN.
