How to use internationalization in VUE

Introduction: For some transnational 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

This article shows how to use internationalization in VUE to change our project language. First we need to install i18n plug-in

Final Effect of this paper

1, i18n

1.1 installation of 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 the official documentation of your vue.js application

/ / use the yarn
yarn add vue-i18n 
//npm
npm i vue-i18n -S
Copy the code

1.2 basic use of I18N

If it is used in a modular system, vuE-i18n must be explicitly installed via vue.use () :

Suppose the current directory is SRC /i18n/index.js

//src/i18n/index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)
// Prepare locale information for translation
const messages = {
  en: { 
    message: {
      hello: 'hello world'}},ja: {
    message: {
      hello: 'Kosher view of the world'}}}// Create an instance of VueI18n with options
const i18n = new VueI18n({
  locale: 'ja'.// Set the locale
  messages // Set the region information
})

Copy the code

The messages object in the code above has two properties called en and JA that correspond in i18n to the locale in the new VueI18n instance below, and the messages object is new Instance property of VueI18n, so when the locale value is JA, the contents of the messages.ja object are loaded

Next, we need to mount the i18N instance in Vue’s Options

import Vue from 'vue'
import i18n from "./i18n/index.js"
new Vue({
	i18n
})
Copy the code

So how do we render it in the view, which is pretty easy, just use the $t function in the interpolation

<div id="app">
  <p>{{ $t("message.hello") }}</p>
</div>
Copy the code

The final result is

<div id="app">
 <p>hello world</p>
</div>
Copy the code

Is it very simple? Of course, this is the most basic use of I18N. If you want to use it in more depth, you can check the official document

2. Used in vue-CLI projects

2.1. Create i18N file structure

We will first create a folder called i18n in the SRC directory of the project, with the path/SRC /i18n Current examples provide only two languages (written much tired -_ – | |), en English and useful Chinese, format the following established, we uphold the high cohesion and low coupling of train of thought, so the original instances i18n messages in the properties of modular split into two files, the following figure, is placed in the config folder

2.2 Content definition of the two files in Config

En.js and en.js We can define some content first

en.js

export default {
    table: {// If you want to translate tables
        date: "Date".name: "Name".address: "Address"
    },
    menu: {},// If there is a menu in the project later
    tabs: {}/ / TAB to switch, etc
}
Copy the code

zh.js

export default {
    table: {
        date: "Date".name: "Name".address: "Address"
    },
    menu: {},
    tabs: {}}Copy the code

2.3. Configure the index.js file in i18n

At present, we have configured two JS files, next, we will configure the/SRC /i18n/index.js file, we all know in the development process, if a route or API has a lot of content written in a file, easy to cause maintenance disaster, continue to uphold the idea of high cohesion and low coupling, we and the project route or In this article, the two language configurations en and zh are also partition modules, but if we have more than 20 countries to translate, our index import one by one is obviously a disaster to the development efficiency of the book, our code may be like this

import en from './config/en'
import id from './config/id'
import ja from './config/ja'
import ae from './config/ae'
import am from './config/am'
import ca from './config/ca'
import al from './config/al'.Copy the code

To solve this problem, this article uses the require.context method in Webpack to solve this problem

2.4, use require.context()

Require. context is a webpack method that lets you import files in bulk. Require. context returns a method with resolve, keys, and ID attributes

  1. Resolve () returns the module ID if the request is resolved
  2. Keys () returns an array of all the requests that fit the context module
  3. Id is the module ID contained in the context module. It may be used when you use module.hot.accept

This method takes three arguments

  1. Dir Passes in a directory for search

  2. Child Whether to search subdirectories

  3. RegExp passes in regular expressions to match which files need to be imported

let langFiles = require.context("./config".false./\.js$/);
Copy the code

We get the following properties when we call the KES () method

let langFiles = require.context("./config".false./\.js$/);
console.log(langFiles.keys())//["./cn.js","./zh.js"]
Copy the code

The above is a simple use of require.context. If you want to know more about its use, I will do another issue on require.context

2.5. Continue the configuration/src/i18n/index.js

I use a regular expression in the following code

let reg = / / ^ \ \ \. ([. ^ \] +) ([. ^ \] +) $/ // The re is used to match the file name
Copy the code

The whole point of using this re is that we need to process the data like this

{
    zh: {... },en: {... }}Copy the code

/zh.js uses the re to intercept the zh characters and generate a data model with the composite message attribute

import Vue from "vue"
import VueI18n from "vue-i18n"
Vue.use(VueI18n)// Inject into all child components

//require.context(path,deep,regExp)
// There are three methods: keys()


let langFileds = require.context('./config'.false./\.js$/)

let regExp = / \ \ / ([^ \ \ /] +) \. ([. ^ \] +) $/ // Re is used to match 'en' in./en.js.

// regExp.exec('./en.js')

let messages = {} // Declare a data model corresponding to the message property in i18n

langFileds.keys().forEach(key= > {
    let prop = regExp.exec(key)[1] / / regular matching en | useful value
    //messages[prop] equivalent to messages['en'] = {table:{... }}
    messages[prop] = langFileds(key).default

})
console.log(messages);
console.log(langFileds('./en.js'));

let locale = localStorage.getItem('lang') | |"zh" // Get it from localStorag

export default new VueI18n({
    locale,// Specify the language field
    messages// Define the language field
})
Copy the code

2.6. Modify main.js

Let’s mount i18N in the Vue instance of main. In this case, we’ve also introduced element-UI. If you want to use element-UI, you need to install it first

yarn add element-ui
Copy the code

Next, write the code according to your requirements

import Vue from 'vue'
import App from './App.vue'
import ElementUI from "element-ui" //element-ui
import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
Vue.use(ElementUI)

import i18n from "./i18n" //

new Vue({
  render: h= > h(App),
  i18n / / a mount
}).$mount('#app')

Copy the code

2.7 App.vue View Display (Navigator. Language)

As you can see from the 2.5 code, I set the locale property to be taken from localStorage for a quick demonstration, but if we are in development and need to use the computer language to determine and switch, the correct way is to use navigator.language Get the language of the computer

<template>
  <div id="app">
    <template>
      <el-table :data="tableData"
                style="width: 100%">
        <el-table-column prop="date"
                         :label="$t('table.date')"
                         width="180">
        </el-table-column>
        <el-table-column prop="name"
                         :label="$t('table.name')"
                         width="180">
        </el-table-column>
        <el-table-column prop="address"
                         :label="$t('table.address')">
        </el-table-column>
      </el-table>

    </template>
    <el-button type="primary"
               @click="change('zh')">Click to switch to Chinese</el-button>
    <el-button type="primary"
               @click="change('en')">Click to switch English</el-button>
    <el-button type="primary"
  </div>
</template>
 <script>
  export default {
    mounted() {
      console.log(this.$i18n.t('table.date'));
    },
    methods: {
      change(lang) { // Switch methods
        localStorage.setItem('lang', lang)
        window.location.reload() //localSotrage is unresponsive, so refresh is called to demonstrate the effect}},data() {
      return {
        tableData: [{
          date: '2016-05-02'.name: 'Wang Xiaohu'.address: Lane 1518, Jinshajiang Road, Putuo District, Shanghai
        }, {
          date: '2016-05-04'.name: 'Wang Xiaohu'.address: Lane 1517, Jinshajiang Road, Putuo District, Shanghai
        }, {
          date: '2016-05-01'.name: 'Wang Xiaohu'.address: Lane 1519, Jinshajiang Road, Putuo District, Shanghai
        }, {
          date: '2016-05-03'.name: 'Wang Xiaohu'.address: Lane 1516, Jinshajiang Road, Putuo District, Shanghai}}}}]</script>
  <style>
  #app {
    width: 50%;
  }
</style>
Copy the code

Effect of 2.8,

Two more languages have been added here