This is the first day of my participation in the First Challenge 2022

Determine the requirements

Select a language from the drop-down menu, and the page automatically switches to the language. The default text of Element also changes.

Chinese English

Function implementation

Version selection

  1. Vue2 (cn.vuejs.org/v2/guide/in…).
  2. Vue – i18n @ 8 (kazupon. Making. IO/vue – i18n/in…)
  3. Element (element. The eleme. Cn / # / useful – cn/com…

Vue2 Select vue-i18n@8

Ii. Project creation

1. Create the locales folder in the SRC directory and add required filesen.json cn.jsonLanguage document

According to the needs of the project, we added json files of various languages to store the language values respectively, and I created Chinesecn.jsonAnd Englishen.json.

Enter the multilingual values we need to use

Cn. Json {" hello ":" hello ", "table" : {" date ":" date ", "name" : "name", "address" : "address"}}Copy the code
en.json
{
  "hello": "hello",
  "table": {
    "date": "Date",
    "name": "Name",
    "address": "Address"
  }
}
Copy the code

The advantage of this is that when you add another language, you simply copy one of the JSON documents and change the values, leaving the structure unchanged.

2. Take out the content of the created multi-language JSON document and output it into the data structure required by vuE-I18N suite;

Create a new i18n.js file

import Vue from "vue"; import VueI18n from "vue-i18n"; Import locale from "element-ui/lib/locale"; import elEn from "element-ui/lib/locale/lang/en"; import elCn from "element-ui/lib/locale/lang/zh-CN"; Vue.use(VueI18n); Function loadLocaleMessages() {// Check how many languages are in the Locales folder const locales = require.context( "./locales", true, /.json$/ ); const messages = {}; locales.keys().forEach(file => { const keyArr = file.split('/'); keyArr.shift(); messages[keyArr.join('.').replace(/\.json$/g, '')] = locales(file); }); return { cn: { ... messages.cn, ... elCn }, en: { ... messages.en, ... elEn }, }; } const i18n = new VueI18n({ locale: "cn" , messages: loadLocaleMessages() }); locale.i18n((key, value) => i18n.t(key, value)); export default i18n;Copy the code

The key point of this step is: how to extract the JSON file content from locales and generate the data we need: determine the type and number of languages according to the json document name, and extract the file content accordingly and store it in the messages object

Used here webpack require. The context (directory, useSubdirectories, regExp) method can get json document and the content of the introduction;

const locales = require.context(
    "./locales",
    true,
    /.json$/
);
Copy the code

Create const Messages = {} objects to put the json data in;

By calling the key() method of the locales return value, we can iterate over all the file paths: it prints out as./cn.json./en.json

This is not the key we want, so we need to do some string interception of the filename cn en

const messages = {}; locales.keys().forEach(file => { const keyArr = file.split('/'); keyArr.shift(); messages[keyArr.join('.').replace(/\.json$/g, '')] = locales(file); }); // Messages :{cn:{... },en:{... }}Copy the code

Finally, a new VueI18n instance is created and exported.

3. Element compatible with VUE-I18N internationalization scheme

This is an example given by the official website element.eleme.cn/#/zh-CN/com…

This allows element components to have placeholder text for some default forms and other default text that changes with the language;

4. Add i18n.js to main.js

Import and mount the Element and I18n files

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

new Vue({
  i18n,
  render: h => h(App)
}).$mount("#app");

Copy the code

5. Use

$t(“hello”), $t(‘table.date’);

<h2>{{ $t("hello") }}</h2>
<el-table
  border
  :data="[]"
  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>
Copy the code

6. Language switching module

Use Element’s El-Dropdown component

app.vue <template> <div id="app"> <div style="text-align: center"> <el-dropdown trigger="click" @command="changeLanguage"> <span class="el-dropdown-link"> {{ language.title }}<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item v-for="(item,index) in languageList" :key="index" :command="index" > {{ item.title }} </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </div> </template> <script> export default { name: 'App', data() {return {language: {value: "zh-cn ", title:" simplified Chinese "}, languageList: [{value: "zh-cn ", title:" simplified Chinese "} "Simplified Chinese"}, {value: "EN - US," the title: "English"}]}}, the methods: { changeLanguage(index){ this.language = this.languageList[index]; switch (this.language.value) { case "ZH-TW": this.$i18n.locale = "tw"; break; case "EN-US": this.$i18n.locale = "en"; break; case "ZH-CN": this.$i18n.locale = "cn"; break; } } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; margin-top: 20px; } </style>Copy the code

@Command triggers the changeLanguage() method every time a drop-down submenu is clicked; Reset this.$i18n.locale each time the language is switched; With this.language, you can switch languages and display the current language in real time.

3. The concluding

OK, the above is the summary of the front-end internationalization scheme I personally used in the project, and I hope it can help you a little bit.

This is my first post in nuggets and I hope you can give me your comments. Thanks – (· ω ·) Blue !!!!!!!!!!