Introduction: For some transnational projects, internationalization is very important, so what should be internationalized? Internationalization means that the projects we write can be translated and switched according to the languages of different countries, so as to facilitate different countries customers use.
1. Introduction to i18n
i18n is the abbreviation of the word internationalization. It takes the initial letter i and the ending letter n. There are 18 letters in the middle, so it is written as i18n when combined. This is a plug-in for vue internationalization. It can easily Integrate some localization features into your Vue.js application
2. Install vue-i18n
Add vue-i18n to dependencies node in package.json
"vue-i18n": "7.3.2",
Then install the dependencies
npm install
or
npm install --registry=https://registry.npm.taobao.org
3. Create internationalization files
Create a lang directory under the src directory to store internationalization files. There are 3 files here, namely index.js, zh.js, en.js
- index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import enLocale from './en'
import zhLocale from './zh'
Vue.use(VueI18n)
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
}
const i18n = new VueI18n({
// 设置语言 选项 en | zh
locale: 'en',
// 设置文本内容
messages
})
export default i18n
- zh.js
export default {
login: {
title: '后台管理系统'
}
}
- en.js
export default {
login: {
title: 'Management System'
}
}
4. Introduce i18n
Add i18n incrementally in src/main.js
import i18n from './lang'
// use添加i18n
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value)
})
new Vue({
i18n,
})
5. Realize internationalization
<template>
<div class="login">
<h3 class="title">{
{ $t('login.title') }}</h3>
</div>
</template>
6. Switch language
- Provide toggle button
<template>
<div class="login">
<h3 class="title">{
{ $t('login.title') }}</h3>
<el-button @click="change('zh')">中文</el-button>
<el-button @click="change('en')">English</el-button>
</div>
</template>
- Provide a switching method
change(language) {
this.$i18n.locale = language
}
7. Basic usage
- normal text usage
{
{
$t('login.title') }}
- In-label usage
:placeholder="$t('login.title')"
- How to use it in js
this.$t('login.title')
If you find deficiencies in reading, please leave a message! ! !