Project Documentation: Implementing i18n for Internationalization
Chinese Document
Table of Contents
- Introduction
- Installation and Configuration
- File Structure
- Adding a New Language
- Using i18n in Components
- Language Switching
- Notes
Introduction
This project uses Vue 3 with the vue-i18n plugin to support multiple languages for internationalization. By configuring language resource files, you can easily switch the text in the project between different languages.
Installation and Configuration
Install Dependencies
First, install the vue-i18n dependency:
npm install vue-i18n
Configure i18n
Create an i18n directory in the root of the project and an index.ts file in it to initialize the i18n configuration.
Directory Structure Example
front-end/src/
├── locales/
│ ├── index.ts
│ ├── en.ts
│ ├── zh.ts
│ └── cy.ts
└── main.ts
Initialize i18n Configuration
In src/locales/index.ts:
import { createI18n } from 'vue-i18n';
import en from './en';
import zh from './zh';
import cy from './cy';
const messages = {
en,
zh,
cy,
};
const i18n = createI18n({
locale: 'en', // Default language
fallbackLocale: 'en', // Fallback language
messages,
});
export default i18n;
In src/main.ts, import and mount i18n:
import { createApp } from 'vue';
import App from './App.vue';
import i18n from './locales/index';
const app = createApp(App);
app.use(i18n);
app.mount('#app');
File Structure
Language Resource Files (Project)
Create language resource files in the src/locales directory, such as en.ts, zh.ts, and cy.ts.
Example: en.ts
import localeAdminHome from '../views/admin/locales/en'
import localeAdminEventApprove from '../views/admin/approve/locales/en'
const en = {
appName: 'WSA Volunteer Hub',
language: {
chinese: 'Chinese',
english: 'English',
welsh: 'Welsh'
},
header: {
actions: {
locale: 'Language switched successfully'
}
},
...localeAdminHome,
...localeAdminEventApprove,
}
export { en }
Note: When you need to import page language files, use
import
import localeAdminHome from '../views/admin/locales/en'
And add to the key object
en:
...localeAdminHome,
Similarly, add the same keys to zh.ts and cy.ts.
Language Resource Files (Pages)
In the pages where you need to add multiple languages, create a new folder called locales, and add the required language files inside it.
Example: en.ts
export default {
"home.userInformation": "User Information",
"home.username": "Username",
"home.role": "Role",
"home.lastLoginTime": "Last Login Time",
"home.lastLoginLocation": "Last Login Location",
// other key-value pairs
};
Example: zh.ts
export default {
"home.userInformation": "用户信息",
"home.username": "用户名",
"home.role": "角色",
"home.lastLoginTime": "最后登录时间",
"home.lastLoginLocation": "最后登录地点",
// other key-value pairs
};
Example: cy.ts
export default {
"home.userInformation": "Gwybodaeth Defnyddiwr",
"home.username": "Enw defnyddiwr",
"home.role": "Rôl",
"home.lastLoginTime": "Amser Mewngofnodi Olaf",
"home.lastLoginLocation": "Lleoliad Mewngofnodi Olaf",
// other key-value pairs
};
Adding a New Language
To add a new language:
- Create the corresponding language file in the
src/localesdirectory, e.g.,fr.ts. - Import the new language in the
index.tsfile and add it to themessagesobject.
For example, to add French support:
src/locales/fr.ts
export default {
"home.userInformation": "Informations utilisateur",
"home.username": "Nom d'utilisateur",
"home.role": "Rôle",
"home.lastLoginTime": "Dernière connexion",
"home.lastLoginLocation": "Dernier lieu de connexion",
// other key-value pairs
};
Modify src/locales/index.ts
import { createI18n } from 'vue-i18n';
import en from './en';
import zh from './zh';
import cy from './cy';
import fr from './fr'; // Newly added
const messages = {
en,
zh,
cy,
fr, // Newly added
};
const i18n = createI18n({
locale: 'en', // Default language
fallbackLocale: 'en', // Fallback language
messages,
});
export default i18n;
Using i18n in Components
Use the $t method to get translated text in Vue components.
Example
Home.vue
<template>
<div>
<h1>{{ $t('home.userInformation') }}</h1>
<p>{{ $t('home.username') }}: {{ username }}</p>
<p>{{ $t('home.role') }}: {{ role }}</p>
<p>{{ $t('home.lastLoginTime') }}: {{ lastLoginTime }}</p>
<p>{{ $t('home.lastLoginLocation') }}: {{ lastLoginLocation }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const username = ref('John Doe');
const role = ref('Admin');
const lastLoginTime = ref('2024-03-24 12:00:00');
const lastLoginLocation = ref('Cardiff');
</script>
Language Switching
The project provides a changeLanguage.vue component for language switching.
Example
Language Switching Component changeLanguage.vue
The changeLanguage.vue file content:
<template>
<div class="custom-container">
<img :src="flagIcon" class="language-icon" alt="language icon" />
<el-select class="custom-select" v-model="lang" @change="changeLocale" popper-class="custom-popper">
<el-option :label="t('language.chinese')" value="zh" />
<el-option :label="t('language.english')" value="en" />
<el-option :label="t('language.welsh')" value="cy" />
</el-select>
</div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance() as any;
const { t } = useI18n();
const lang = ref(localStorage.getItem('lang') || 'zh');
const currentLocale = computed(() => {
return proxy.$i18n.locale;
});
import cnIcon from '../../assets/cn-icon.png';
import ukIcon from '../../assets/uk-icon.png';
import cyIcon from '../../assets/cy-icon.png';
const flagIcons: { [key: string]: string } = {
zh: cnIcon,
en: ukIcon,
cy: cyIcon,
};
const flagIcon = computed(() => {
return flagIcons[lang.value];
});
const changeLocale = (locale: string) => {
proxy.$i18n.locale = locale;
localStorage.setItem('lang', locale);
ElMessage.success(t('header.actions.locale'));
};
changeLocale(lang.value);
</script>
<style scoped>
...
</style>
Using the changeLanguage.vue Component
Import and use the changeLanguage.vue component on the pages where language switching is needed:
Example: Using in Home.vue
<template>
<div>
<changeLanguage />
<!-- other content -->
</div>
</template>
<script setup>
import changeLanguage from './components/changeLanguage.vue';
</script>
By following the above configuration, you can easily switch languages in your project and ensure that all component text content dynamically updates according to the selected language.
Notes
- Ensure that all text is referenced through the
$tmethod to guarantee consistency in internationalization. - Maintain a consistent naming convention for new language keys to make management easier.
- Regularly update the language resource files to ensure translation accuracy and completeness.
By following these steps and configurations, you can achieve comprehensive internationalization support in your project and easily add and manage multiple languages.