Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

The previous article “how to do internationalization of the front end (1)” mainly talked about the function of tailoring customization

How to internationalize the front-end (ii)

Serialized reading experience is better

Internationalization of copywriting

Vue projects are internationalized using vuE-I18N plug-ins: VUE-I18N documents.

Install the vue – i18n:

npm i vue-i18n
Copy the code

After that, we create the locale folder under SRC, which has the following directory structure:

├── locale │ ├─ region.js To save the state Settings that came in via webPack in the previous section Langinterceptor.js is used to control which language package is loaded and set up the display language │ ├─ langmap.js language mapping table for each language name. │ ├─ ├─ en_us.js │ ├─ ├─ us.js │ ├─ en_us.js │ ├─ ├─ us.jsCopy the code

district.js

Region configuration.

// Read locale configuration from webpack environment variables in the format {name: ", config: "}
export const district = process.env.DISTRICT
 
// Obtain the region configuration item by key
export const getDistrictConfig = key= > {
  return district.config[key]
}
 
// Get the language list item
export const languages = getDistrictConfig('languages')
 
// Fetch the cookie domain
export const cookieDomain = getDistrictConfig('cookieDomain')
 
// Domain names/URLS for different locales
export const urls = getDistrictConfig('urls')
 
// Feature tailoring for different regions
export const functional = getDistrictConfig('functional')
 
export const passport = getDistrictConfig('passport')
Copy the code

lang/zh_CN.js

// If there is a reference to a component library such as element-ui, the corresponding translation file for the component library needs to be imported
import zhCN from 'element-ui/lib/locale/lang/zh'
 
export default {
  ...zhCN,
  locale: 'language'.title: 'New Zeus is more powerful'. }Copy the code

The key is up to the developer.

index.js

/** * VueI18n internationalized configuration ** /
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zh_CN from '@/locale/lang/zh_CN'
import en_US from '@/locale/lang/en_US'
import th_TH from '@/locale/lang/th_TH'
// If a component library such as element-UI is introduced, its translation function needs to be modified
import locale from 'element-ui/lib/locale'
 
const languageMsg = {
  zh_CN,
  en_US,
  th_TH
}
 
const msg = {}
languages.forEach(lang= > {
  msg[lang] = languageMsg[lang]
})
 
Vue.use(VueI18n)
 
// Configure the language
const i18n = new VueI18n({
  locale: languages[0].// The first language is taken by default
  messages: msg
})
 
locale.i18n((key, value) = > i18n.t(key, value))
 
export default i18n
Copy the code

langMap.js

Used to map the language selection list, the switch language selection text should be consistent with its language

export default {
  zh_CN: 'Simplified Chinese'.en_US: 'English',}Copy the code

utils.js

Internationalization utility class functions.

/** * VueI18n internationalized language configuration */
/* eslint-disable */
import Cookies from '@/utils/js-cookie'
import i18n from './i18n'
import axios from 'axios'
import { cookieDomain } from './district'
/** * Redirects the Url by language. This function can be used to switch languages *@param {String} Lang language identifier */
export function setLocaleUrl(lang) {
  Cookies.set('language', lang, {
    domain: cookieDomain,
    expires: 1
  })
  let href = location.href.replace(/language=([^&]*)/.`language=${lang}`)
  location.href = href
}
 
/** * Set the language *@param {String} Lang language identifier */
function setLocale(lang) {
  i18n.locale = lang
  // Modify the Ajax request header, if you are any other HTTP package
  axios.defaults.headers.common['Accept-Language'] = lang
  // Change the page title
  document.title = i18n.t('title')
  return lang
}
Copy the code

langInterceptor.js

Language route interceptor, before entering the page, get the language, and set the language.

/** * language unified route interception */
import Cookies from '@/utils/js-cookie'
import { languages } from './district'
 
let LangInterceptor = {}
 
LangInterceptor.install = (Vue) = > {
  Vue.mixin({
    beforeRouteEnter (to, from, next) {
      let currentLanguage = ' '
      // languages refers to the list of languages currently used in the region
      // Cookies refer to methods of manipulating Cookies
      // Select the language identifier from query and check whether it belongs to the language list
      if (to.query.language && languages.indexOf(to.query.language) > -1) {
        currentLanguage = to.query.language
      }
      // If there is no language identifier in query, it is fetched from cookie; if there is no language identifier in cookie, it is fetched from default language
      if(! currentLanguage) {let cookieLang =  Cookies.get('language')
 
        if (cookieLang && languages.indexOf(cookieLang) > -1) {
          currentLanguage = cookieLang
        } else {
          currentLanguage = languages[0]
        }
      }
      next()
    }
  })
}
 
export default LangInterceptor
Copy the code

Then use the LangInterceptor in the project entry file main.js:

main.js

import Vue from 'vue'
import App from './App.vue'
import i18n from './locale/index'
import LangInterceptor from './locale/langInterceptor'
 
Vue.config.productionTip = false
 
Vue.use(LangInterceptor)
 
new Vue({
  i18n,
  render: h= > h(App)
}).$mount('#app')
Copy the code

Then I translated the copy that needed to be translated in the project:

<div id="app">
  <p>{{ $t('title') }}</p>
</div>
Copy the code

Examples of business code for switching between Chinese and English:

<template> <! -- Element UI --><el-dropdown @command="handleCommand">
    <span class="el-dropdown-link">
      {{langMap[$i18n.locale]}}
      <i class="el-icon-arrow-down el-icon--right"></i>
    </span>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item
        v-for="(lang, index) in languages"
        :key="index"
        :command="lang"
      >{{ langMap[lang] }}</el-dropdown-item>
  </el-dropdown-menu>
</template>
 
<script>
import langMap from "@/locale/langMap"
import { setLocaleUrl } from "@/locale/utils"
import { languages } from "@/locale/district"
 
export default {
  name: "Header".data() {
    return {
      langMap,
      languages
    }
  },
  methods: {
    handleCommand(command){ setLocaleUrl(command); }}};</script>
Copy the code

Back to feature tailoring

Function pruning generally requires pruning function entries and corresponding page routes.

Cutting entrance:

<template>
  <header class="header">
    <router-link v-if="functional.vapp" to="/vapp">Small program</router-link>
  </header>
</template>
 
<script>
import { functional } from '@/locale/district'
 
export default {
  data () {
    return {
      functional
    }
  }
}
</script>
Copy the code

Clipping route:

router.js

import Vue from 'vue'
import Router from 'vue-router'
import { functional } from '@/locale/district'
import Index from '@/views/index.vue'
 
const router = new Router({
  routes: [{path: '/'.component: Index
    },
    // Crop the vapp page. (functional.vapp ? [{path: '/vapp'.component: () = > import('@/views/vapp.vue')} : []]})Copy the code

How do I get the variable configuration in index.html

The index. HTML file is handled by the HTml-webpack-plugin, which since 3.0 supports passing configuration into HTML.

Vue-cli3 starts, automatically passing the configuration of vue.config.js to index.html

The html-webpack-plugin customizes incoming data by adding the templateParameters function.

const localeConfig = require('path/to/locale')

    new HtmlWebpackPlugin({
      filename: 'index.html'.template: 'index.html'.inject: true.templateParameters: (compilation, assets, pluginOptions) = > {
        let stats
        return {
          get webpack () {
            return stats || (stats = compilation.getStats().toJson())
          },
          compilation: compilation,
          webpackConfig: {
            ...compilation.options
          },
          htmlWebpackPlugin: {
            files: assets,
            options: pluginOptions
          },
          config: {
            stream: localeConfig.config.stream
          }
        }
      }
    })
Copy the code

The project created by vue-cli 2 needs to be upgraded with html-webpack-plugin, and manually run NPM I html-webpack-plugin@3 -d

The previous article “how to do internationalization of the front end (1)” mainly talked about the function of tailoring customization

How to internationalize the front-end (ii)

Serialized reading experience is better

Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.

Past wonderful recommendation

React Development specification

Vue development specification

Mobile end horizontal and vertical screen adaptation and bangs adaptation

Mobile frequently asked Questions

Front-end common encryption methods

Canvas Pit Climbing Road

Don’t know SEO optimization? An article helps you understand how to do SEO optimization

Canvas Pit Road

Wechat small program development guide and optimization practice

Talk about mobile adaptation

Front-end performance optimization for actual combat

Talk about annoying regular expressions

Obtain file BLOB stream address to achieve the download function

Vue virtual DOM confused? This article will get you through the virtual DOM once and for all

Git Git

Easy to understand Git introduction

Git implements automatic push

Interview Recommendations

Front ten thousand literal classics – the foundation

Front swastika area – advanced section

More exciting details: personal homepage