Skip to content

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 Plus zh-cn
  • en → Element Plus en
  • ja → Element Plus ja

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

  1. Application Startup: Read user language preferences from localStorage
  2. Plugin Initialization: Configure Vue I18n instance
  3. Language Pack Loading: Dynamically import corresponding language translation files
  4. Element Plus Configuration: Set UI component library language pack
  5. Global Registration: Register translation functions as global properties

Language Switching Mechanism

  1. State Update: Update language state in Pinia store
  2. DOM Update: Set HTML page's lang attribute
  3. Event Notification: Trigger global language change event
  4. 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:

shell
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 translations

Namespace 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:

typescript
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:

typescript
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

typescript
export default {
  product: {
    pageTitle: '产品管理',
    productName: '产品名称',
    productCode: '产品编码',
    price: '价格',
    status: '状态',
    addProduct: '新增产品',
    editProduct: '编辑产品',
    deleteProduct: '删除产品',
    deleteConfirm: '确认删除产品"{name}"吗?',
    addSuccess: '产品新增成功',
    updateSuccess: '产品更新成功',
    deleteSuccess: '产品删除成功',
  },
}

en.ts

typescript
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:

typescript
const otherModules: string[] = ['product']

3. Usage in Components

vue
<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:

  1. State Update: Update global language state through Pinia store
  2. DOM Synchronization: Automatically update HTML page's lang attribute
  3. Component Response: Trigger global language change event, all components using translations automatically re-render
  4. 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

  1. Module Prefix: Use module name as namespace prefix
  2. Semantic Naming: Key names should clearly express their meaning
  3. Consistency: Use the same translation key for text with the same meaning

Dynamic Parameter Handling

Use Vue I18n's parameter interpolation function:

typescript
// 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:

typescript
// Translation file
itemCount: '{count} item | {count} items'

// Usage in component
const message = t('common.itemCount', { count: itemCount }, itemCount)

Error Handling

  1. Key Not Found Handling: Provide default fallback text
  2. Load Failure Handling: Graceful degradation to default language
  3. 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

  1. Translation Key Not Found: Check key name spelling and namespace
  2. Language Switching Invalid: Confirm language pack loaded successfully
  3. Element Plus Language Mismatch: Check language pack mapping configuration

Debugging Tips

  1. Use Vue Devtools to check translation state
  2. Check language pack loading logs in browser console
  3. Verify language settings in localStorage

Extension Guide

Adding New Languages

  1. Create corresponding language directory under src/locales/
  2. Add language pack mapping configuration
  3. Update language selector support
  4. 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.