Takip et

More I18N Ile Vue: Içinmatting Ve Fallbacks

You’re looking to dive deeper into Internationalization (i18n) with Vue! vue-i18n is the go-to library, and it offers a lot more than just basic strin

You’re looking to dive deeper into Internationalization (i18n) with Vue! vue-i18n is the go-to library, and it offers a lot more than just basic string translation.

Let’s explore some advanced features and best practices for robust i18n in your Vue applications.

Vue i18n: Beyond the Basics

We’ll assume you have a basic vue-i18n setup like this:

1. Installation:

npm install vue-i18n@next # For Vue 3

or

yarn add vue-i18n@next

2. main.js (or main.ts) Setup:

// main.js
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import App from './App.vue'

// 1. Define your messages
const messages = {
  en: {
    welcome: 'Welcome!',
    greeting: 'Hello, {name}!',
    apple: 'no apples | {count} apple | {count} apples',
    message: {
      named: 'Hello {name}, you are using version {version}.',
      list: 'The items are {0} and {1}.'
    }
  },
  es: {
    welcome: '¡Bienvenido!',
    greeting: '¡Hola, {name}!',
    apple: 'sin manzanas | {count} manzana | {count} manzanas',
    message: {
      named: 'Hola {name}, estás usando la versión {version}.',
      list: 'Los artículos son {0} y {1}.'
    }
  }
}

// 2. Create i18n instance with options
const i18n = createI18n({
  locale: 'en', // set locale
  fallbackLocale: 'en', // set fallback locale
  messages, // set locale messages
  legacy: false, // Use Composition API mode for Vue 3
  globalInjection: true, // Allows using $t, $d, $n globally without explicit import
})

// 3. Mount your app
const app = createApp(App)
app.use(i18n)
app.mount('#app')

3. Basic Usage in Components:


Advanced Features

### 1. Interpolation (Variables in Translations)

You’ve seen basic named interpolation ({name}). vue-i18n supports more:

* Named Interpolation: Hello, {name}!

// messages
    named: 'Hello {name}, you are using version {version}.'
    // usage
    $t('message.named', { name: 'Vue', version: '3' })

* List Interpolation: The items are {0} and {1}.

// messages
    list: 'The items are {0} and {1}.'
    // usage
    $t('message.list', ['item1', 'item2'])

* Custom HTML (with i18n-t component): For injecting HTML directly into a translation.


    // key: 'link_to_docs': 'Please read our documentation for more info.'

    
    
      
    

### 2. Pluralization

vue-i18n handles pluralization using ICU MessageFormat syntax.

// messages.en.js
apple: 'no apples | {count} apple | {count} apples'
// messages.es.js
apple: 'sin manzanas | {count} manzana | {count} manzanas' // Note: Spanish often uses '1' vs 'other'

Usage:

{{ $t('apple', 0) }}

{{ $t('apple', 1) }}

{{ $t('apple', 5) }}

{{ $t('apple', { count: 10 }) }}

You can also define custom pluralization rules for specific languages if the default ICU rules aren’t sufficient.

### 3. Date & Time Formatting

Use the $d helper and define datetimeFormats in your i18n configuration.

1. Configuration (main.js):

const i18n = createI18n({
  // ... other options
  datetimeFormats: {
    en: {
      short: {
        year: 'numeric', month: 'short', day: 'numeric'
      },
      long: {
        year: 'numeric', month: 'long', day: 'numeric',
        hour: 'numeric', minute: 'numeric', hour12: true
      },
      full: {
        year: 'numeric', month: 'long', day: 'numeric',
        hour: 'numeric', minute: 'numeric', second: 'numeric',
        weekday: 'long', timeZoneName: 'short'
      }
    },
    es: {
      short: {
        year: 'numeric', month: 'numeric', day: 'numeric'
      },
      long: {
        year: 'numeric', month: 'long', day: 'numeric',
        hour: 'numeric', minute: 'numeric', hour12: false
      }
    }
  }
})

2. Usage in Components:

### 4. Number Formatting

Similar to dates, use the $n helper and numberFormats.

1. Configuration (main.js):

const i18n = createI18n({
  // ... other options
  numberFormats: {
    en: {
      currency: {
        style: 'currency', currency: 'USD', currencyDisplay: 'symbol'
      },
      decimal: {
        style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2
      },
      percent: {
        style: 'percent', useGrouping: false
      }
    },
    es: {
      currency: {
        style: 'currency', currency: 'EUR', currencyDisplay: 'symbol'
      },
      decimal: {
        style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2
      }
    }
  }
})

2. Usage in Components:

### 5. Dynamic Locale Switching

You can change the locale at runtime.



Tip: When initializing your i18n instance, you can check localStorage for a user’s preferred locale:

const userPreferredLocale = localStorage.getItem('user-locale') || 'en';

const i18n = createI18n({
  locale: userPreferredLocale,
  fallbackLocale: 'en',
  // ...
});

### 6. Component-Level i18n

Sometimes, you have messages specific to a single component that you don’t want to clutter your global message files with.




### 7. Fallback Locales & Message Fallbacks

* fallbackLocale: If a translation key isn’t found in the current locale, vue-i18n will try to find it in the fallbackLocale.

// main.js
    const i18n = createI18n({
      locale: 'fr', // Current locale
      fallbackLocale: 'en', // If a key is missing in 'fr', look in 'en'
      // ...
    })

Message Fallback: If a key isn’t found in any* locale (current or fallback), vue-i18n will simply return the key itself (e.g., $t('nonExistentKey') returns “nonExistentKey”). This is useful for development to spot missing translations.

### 8. Lazy Loading Translations (Code Splitting)

For large applications with many locales, loading all translations upfront can increase bundle size. You can lazy-load them when a user switches locale.

1. Structure your locale files:

src/
├── locales/
│   ├── en.json
│   ├── es.json
│   └── fr.json
└── main.js
└── App.vue

en.json:

{
  "welcome": "Welcome!",
  "greeting": "Hello, {name}!"
}

2. Modify main.js to initially load only the default locale:

// main.js
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import App from './App.vue'

// Only load 'en' initially
import enMessages from './locales/en.json'

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: {
    en: enMessages
  },
  legacy: false,
  globalInjection: true,
})

const app = createApp(App)
app.use(i18n)
app.mount('#app')

3. Create a function to load other locales dynamically:



### 9. Externalizing Translation Files

Instead of embedding all messages directly in main.js, it’s cleaner to have separate files for each locale. This is implicitly done in the lazy loading example, but you can do it for initial load too.

// main.js
import { createApp } from 'vue'
import { createI18n } from 'vue-i18n'
import App from './App.vue'

import enMessages from './locales/en.json'
import esMessages from './locales/es.json'

const i18n = createI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: {
    en: enMessages,
    es: esMessages
  },
  // ...
})
// ...

Best Practices

1. Key Naming:
* Use descriptive, hierarchical keys (e.g., user.profile.title, button.submit, error.network_failed).
* Avoid using the actual English text as the key, as it makes refactoring harder.
* Keep keys consistent across locales.

2. Message Structure:
* Organize your message files logically, either by feature, page, or component.
* JSON files are generally preferred for clarity and tooling compatibility.

3. Default Locale:
* Choose a default locale (often English) and ensure all keys are present in it. This acts as your source of truth.
* Use fallbackLocale to ensure a translation is always available, even if a specific locale is missing a key.

4. Handling Missing Translations:
* During development, the default behavior of vue-i18n (returning the key itself if a translation is missing) is helpful.
* For production, consider setting missingWarn: false to silence console warnings, but ensure you have a robust translation process to prevent missing keys.
* You can also provide a missing handler function to customize this behavior.

5. SEO & Accessibility:
* Always update the lang attribute on your tag when the locale changes (document.documentElement.setAttribute('lang', newLocale)). This helps search engines and screen readers.
* Ensure your translations are semantically correct and provide good context for accessibility tools.

6. Testing:
* Write tests for your i18n implementation, especially for complex pluralization, date/number formatting, and dynamic content.
* Test locale switching to ensure all UI elements update correctly.

7. Tooling & Automation:
* Extraction: Use tools (e.g., vue-i18n-extract or custom scripts) to automatically extract keys from your templates and scripts into JSON files.
* Linting: Integrate linters to check for missing keys or unused keys.
* Translation Management Systems (TMS): For larger projects, consider integrating with a TMS (e.g., Lokalise, Phrase, Transifex) to manage translations, collaborate with translators, and automate the import/export of locale files.

By implementing these advanced features and following best practices, you can build a truly internationalized Vue application that is robust, scalable, and user-friendly for a global audience.

Yorumlar
İçeriği beğendiniz mi? Bir tartışma başlatın veya görüşlerinizi paylaşın.
Yorum Yaz

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

Gönder

E-posta Bülteni
Yazılım Topluluğuna Katılın
En son güncellemeleri, yaratıcı ipuçlarını ve özel kaynakları doğrudan e-posta kutunuza alın. Tasarım ve inovasyonun geleceğini birlikte keşfedelim.
Exit mobile version