SoFunction
Updated on 2025-04-13

One article will help you understand how to use i18n in Vue

1. Basic introduction to i18n

i18n (the abbreviation of Internationalization, 18 represents the number of letters between the beginning and ending letters) is the abbreviation of "internationalization". Its main purpose is to enable applications to adapt to the needs of different languages ​​and regions. Why do I need i18n? Globalization needs, applications need to serve users in different countries, meet the business expansion needs of multilingual markets, and enhance the international competitiveness of products. i18n is not just a translation tool, but a complete international solution. It can help us better develop and maintain international applications and improve user experience and development efficiency. In modern web development, i18n has become a necessary tool for building global applications.

2. Installation and configuration

# 1. Install vue-i18nnpm install vue-i18n@next    # Vue 
# ornpm install vue-i18n@8      # Vue 

3. Basic configuration

// i18n/
 
import { createI18n } from 'vue-i18n'
 
// Language Pack Configurationconst messages = {
  // Chinese language pack  zh: {
    message: {
      hello: 'Hello',
      welcome: 'Welcome{name}',
      // Navigation      nav: {
        home: 'front page',
        about: 'about Us',
        user: 'User Center'
      },
      // Form      form: {
        username: 'username',
        password: 'password',
        submit: 'submit',
        reset: 'Reset'
      }
    }
  },
  // English language pack  en: {
    message: {
      hello: 'Hello',
      welcome: 'Welcome to {name}',
      nav: {
        home: 'Home',
        about: 'About',
        user: 'User Center'
      },
      form: {
        username: 'Username',
        password: 'Password',
        submit: 'Submit',
        reset: 'Reset'
      }
    }
  }
}
 
// Create an i18n instanceconst i18n = createI18n({
  locale: 'zh', // Set the default language  fallbackLocale: 'en', // Set an alternative language  messages, // Language Pack  legacy: false, //Use a combination API  globalInjection: true // Global injection of $t function})
 
export default i18n

4. Register in

import { createApp } from 'vue'
import App from './'
import i18n from './i18n'
 
const app = createApp(App)
(i18n)
('#app')

5. Basic usage

<!-- 1. Used in templates -->
<template>
  <!-- Basic translation -->
  <h1>{{ $t('') }}</h1>
  
  <!-- Translation with parameters -->
  <p>{{ $t('', { name: 'Vue' }) }}</p>
  
  <!-- Switch language -->
  <select v-model="$">
    <option value="zh">Chinese</option>
    <option value="en">English</option>
  </select>
</template>
 
<!-- 2. CombinationAPIUsed in -->
<script setup>
import { useI18n } from 'vue-i18n'
 
const { t, locale } = useI18n()
 
// Use translation(t(''))
 
// Switch languageconst changeLanguage = (lang) => {
   = lang
}
</script>

6. Advanced usage

// 1. Digital formattingconst i18n = createI18n({
  numberFormats: {
    zh: {
      currency: {
        style: 'currency',
        currency: 'CNY'
      }
    },
    en: {
      currency: {
        style: 'currency',
        currency: 'USD'
      }
    }
  }
})
 
// use<template>
  <p>{{ $n(100, 'currency') }}</p>
</template>
 
// 2. Date formattingconst i18n = createI18n({
  datetimeFormats: {
    zh: {
      short: {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      }
    },
    en: {
      short: {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      }
    }
  }
})
 
// use<template>
  <p>{{ $d(new Date(), 'short') }}</p>
</template>

7. Dynamically load language packs

// i18n/
export const loadLanguageAsync = async (lang) => {
  // Dynamic import of language files  const messages = await import(`./locales/${lang}.js`)
  
  // Set language pack  (lang, )
  
  // Switch language   = lang
  
  // Storage language selection  ('language', lang)
  
  return 
}
 
// useconst changeLanguage = async (lang) => {
  await loadLanguageAsync(lang)
}

8. Language Pack Management

// locales/
export default {
  message: {
    // Universal    common: {
      confirm: 'confirm',
      cancel: 'Cancel',
      save: 'save'
    },
    // error message    error: {
      network: 'Network Error',
      timeout: 'Request timed out',
      notFound: 'Resource does not exist'
    },
    // Business module    user: {
      login: 'Log in',
      register: 'register',
      profile: 'Profile'
    }
  }
}

9. Persistence language selection

// i18n/
export const setupI18nPersistence = (i18n) => {
  // Get language settings from local storage  const savedLanguage = ('language')
  
  if (savedLanguage) {
     = savedLanguage
  } else {
    // Get the browser language    const browserLang = ('-')[0]
     = browserLang
    ('language', browserLang)
  }
}

10. Best Practices

// 1. Create a language switch componentconst LanguageSwitcher = {
  setup() {
    const { locale, t } = useI18n()
    
    const languages = [
      { code: 'zh', name: 'Chinese' },
      { code: 'en', name: 'English' }
    ]
    
    const changeLanguage = async (lang) => {
      await loadLanguageAsync(lang)
      ('html').setAttribute('lang', lang)
    }
    
    return { locale, languages, changeLanguage }
  }
}
 
// 2. Internationalization of routing titles((to, from, next) => {
  const { t } = 
   = t() || 'Default title'
  next()
})
 
// 3. Internationalization of Error Messageconst handleError = (error) => {
  const { t } = 
  showMessage(t(`error.${}`))
}

11. Use suggestions

Reasonably organize language pack structure

Use namespaces to avoid conflicts

Implement language selection persistence

Consider dynamic load optimization performance

Pay attention to the localization of dates and numbers

Do a good job of internationalizing misinformation

Keep language packs updated in sync

This is the article about this article that will help you understand the usage of i18n in Vue. For more information about using Vue i18n, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!