This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

1. Introduction to internationalization

For some international projects, internationalization is particularly important, so what should internationalization be? Internationalization means that the projects we write can be translated and switched according to the languages of different countries, so as to facilitate the use of customers in different countries

The basic idea is as follows

① Define language package: if you need several languages to display, define several language packages

The key of the object is the reference of the language package, and the value is the language package object

③ Create an object of class VUE-i18N, assign the messages attribute to the object created in step ②, and the locale attribute to the key corresponding to the language object in step ②

④ When creating Vue instance objects, mount Vue – I18N objects

So let’s talk about it

2. Easy to use

1. Install the plug-in VUE-i18n

I18n is a shortening of the word internationalization. It starts with the initial letter I and ends with the letter N, and is made up of 18 letters in the middle, so when combined it’s called I18N. It’s a plug-in for internationalization of vUE. It makes it easy to integrate some localization features into your vue.js application

npm i vue-i18n
Copy the code

Import it in main.js and use it as a plug-in

import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
Copy the code

2. Create a language pack object

// const en = {username: 'username ', email:' email ', mobile: 'mobile'} 'Username', email: 'Email', mobile: 'Mobile' }Copy the code

The keys in the two first items are the same and will be used later in the component

3. Combine objects

Const messages = {zh, en}Copy the code

4. Create an i18N instance

Const i18n = new VueI18n({messages, locale: 'en'}) const i18n = new VueI18n({messages, locale: 'en'})Copy the code
  • The Messages property is set to the fix ing combination in Step 3
  • Locale: is the value of a key in the messages object. If it is set to en, the component uses the value of the corresponding attribute in the English language package created in Step 1; if it is set to en, only the attribute in the Chinese language package is used

5. Mount objects

$i18n new Vue({i18n, render: h => h(App)}).$mount('# App ')Copy the code

6. Complete code

Import Vue from 'Vue' import App from './ app. Vue 'import VueI18n from 'vue-i18n' vuue. use(VueI18n) // 1, create a Chinese package object const En = {username: 'username ', email:' mobile ', const en = {username: 'username ', email:' mobile '} // 'Email', mobile: 'Mobile'} const messages = {en, en} Const i18n = new VueI18n({messages, locale: $i18n new Vue({i18n, render: h => h(App)}).$mount('# App ')Copy the code

7. Used in components

<template>
  <div id="app">
    <p>{{ $t('username') }}</p>
    <p>{{ $t('email') }}</p>
    <p>{{ $t('mobile') }}</p>
  </div>
</template>
Copy the code

3. Extend the language package object

In a real project, there might be many places that need to be internationalized, such as table headers, TAB bars, navigation menus, etc. We can create multiple keys in the language pack to store the languages of these modules

// 1, menus: const zh = {table: {username: 'username ', email:' mailbox ', mobile: 'mobile'}, {home: 'home ', download: }, tabs: {info: 'tabs ', comment:' comment '}} // 2) Const en = {table: {username: 'username ', email: 'Email', mobile: 'Mobile' }, menus: { home: 'Home', download: 'DownLoad' }, tabs: { info: 'Describe', comment: 'Comment On' } }Copy the code

Use in components

<template> <div id="app"> <! - used in analog form -- -- > < div > < p > {{$t (' table. The username ')}} < / p > < p > {{$t (' table. Email ')}} < / p > < p > {{$t (' table. Mobile ')}} < / p > </div> <! - used in the simulation navigation menu -- > < div > < p > {{$t (' menus. Home ')}} < / p > < p > {{$t (' menus. Download ')}} < / p > < / div > <! - used in simulating tabs TAB - > < div > < p > {{$t (' tabs. The info ')}} < / p > < p > {{$t (' tabs.com ment)}} < / p > < / div > < / div > < / template >Copy the code

In this case, you can change the locale value to zh

Const i18n = new VueI18n({messages, locale: 'zh'}); // create VueI18n instance and assign messages and locale attributes const i18n = new VueI18n({messages, locale: 'zh'})Copy the code

In actual development, there may be multiple tables and navigation menus in multiple components, and the description information of table headers and menus in each table may be different

How to deal with it?

Take the table header for example

We can define multiple tables in the language package object, such as userTable, roleTable, etc., each of which stores its own fields and the corresponding language. We can also define multiple fields in a table object, and define all the table header information used by all tables in a table object

4. Separate language package files

Language pack objects can end up being large and have a lot of properties, so it’s best to define them as separate JS files and then consolidate them

1. Create a language pack file

Create a new langurage directory under the SRC directory, create zh.js and en.js files in it, and then copy the package code from above, because we will use the package object later, so export it

zh.js

// 1, export default{table: {username: 'username ', email:' mailbox ', mobile: 'mobile'}, {home: 'home ', download: }, tabs: {info: 'tabs ', comment:' comment '}}Copy the code

en.js

// 2, export default {table: {username: 'username ', email:' email ', mobile: 'mobile'}, menus: {home: 'Home', download: 'DownLoad' }, tabs: { info: 'Describe', comment: 'Comment On' } }Copy the code

2. Integrate language pack files

We wrote the process of integrating the language pack objects and creating and configuring the VueI18n instance to a JS file and imported it in main.js

So the main.js code will be much simpler, after all, main.js only needs a VueI18n instance at the end! []

Create index.js in the langurage directory as follows

Import Vue from 'Vue' import VueI18n from 'vue-i18n' import en from './en' import Vue from 'Vue' import VueI18n from 'vue-i18n' import en from './en' Vue.use(VueI18n) const messages = { zh, en } const i18n = new VueI18n({ messages, locale: 'en' }) export default i18nCopy the code

3, introduced in main.js

import Vue from 'vue' import App from './App.vue' import i18n from './langurage' Vue.config.productionTip = false // I18n new Vue({i18n, render: h => h(App)}).$mount('# App ')Copy the code

5. Switch languages

To change the current language, change the locale value in the following code

const i18n = new VueI18n({
  messages,
  locale: 'en'
})
Copy the code

Of course, manual switching is not possible, the page can provide a button, when clicked, dynamically change the value here

The navigator. Language method is used to get the language the browser is currently using, which basically represents the language the user is using

Const i18n = new VueI18n({messages, locale: navigator.language // Get the browser's language})Copy the code

Language switch button added to component

<button @click="translate('en')"> </button>Copy the code
  methods: {
    translate(lang) {
      this.$i18n.locale = lang
    },
  },
Copy the code

Thus, we have achieved the language switch

6. How to deal with dynamic menu

The navigation menu below is rendered dynamically by requesting background data and borrowing the Menu component of the Element-UI

The value of the menu name field (authName) is Chinese, how to handle this?

Quite simply, the relevant data is defined in the language package

zh.js

Export default {menus: {User management: 'user management ', user list:' user list ', role list: 'role list ', Permission management:' permission management ', permission list: 'permission list'}}Copy the code

en.js

Import default {menus: {User management: 'User Manager', User List: 'User List', Role List: 'Role List', permission management: 'Rights Manager', permission List: 'Rights List' } }Copy the code

When rendering the Menu component, add the following code

Define the method menusTitle in methods

  menusTitle(item) {
      if (this.$te('menus.' + item)) {
        return this.$t('menus.' + item)
      }
      return item
    },
Copy the code

Now we implement the translation function

Add a switch to the header for language switching

<el-switch
    v-model="langValue"
    :active-text="active_text"
    :inactive-text="inactive_text"
    @change="translate"
>
Copy the code

Data in data

 langValue: false,
 lang: '',
 active_text: '',
 inactive_text: '',
Copy the code

The above values are initialized when the component is initialized

This method is defined in methods and called in the Created hook function

setSwitch() { this.active_text = navigator.language === 'zh' ? This.inactive_text = navigator. Language === 'en'? This.lang = navigator. Language},Copy the code

Switch’s change event handler

translate() {
    this.lang = this.lang === 'zh' ? 'en' : 'zh'
    this.$i18n.locale = this.lang
},
Copy the code

7. How to adjust the language setting

In the browser’s language Settings, you can adjust the language, then refresh the page, and the browser will adopt the latest language Settings