Configure i18n internationalization in Vue project (with comments)

1: Install vue-i18n

npm install vue-i18n

2: Create language files

Create a new lang folder in the src directory, en.json is the English language pack, zh.json is the Chinese language pack

The format of the file is like this

// en.json
export default {
    'name': 'name',
    'user': 'user',
    .....
    
}
// zh.json
export default {
    'name': '姓名',
    'user': '用户',
    .....
}

3: Configure the vue-i18n instance

import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);

import zh from './config/zh';
import en from './config/en';

const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: {
    en: require('./locales/en.json'),
    zh: require('./locales/zh.json')
  }
});

export default i18n;

 4: Using translation messages in components

In the template of the Vue component, use  $tthe method to access the translation message and display the text content on the page:

<template>
  <div>
    <p>{
   
   { $t('name') }}</p>
    <p>{
   
   { $t('user') }}</p>
  </div>
</template>

5: Switch language

<template>
  <div>
    <button @click="switchLanguage('en')">English</button>
    <button @click="switchLanguage('zh')">中文</button>
    
    <p>{
   
   { $t('user') }}</p>
    <p>{
   
   { $t('name') }}</p>
  </div>
</template>
methods: {
  switchLanguage(lang) {
    this.$i18n.locale = lang;
  }
}

You can also save the state in  localStorage which is more convenient

Guess you like

Origin blog.csdn.net/Guanchong333/article/details/130661456