preface

The company’s project involves internationalization, and I had never done it before, so I looked up some information a little, and then I realized internationalization from 0. Write it down for later use. (end with source code) the first time to write, may not be satisfactory, do not like to spray, welcome communication.

The body of the

Install dependencies

If it depends on vue-i18N, run the yarn add vue-i18n or NPM install Vue-i18n command to install it first

The preparatory work

Create under SRC:

Locale /langs/zh.js and locale/langs/en.js are used to store the content to be translated

Const lang = {title: 'title',// title1: 'title1',// (title2) placeholder: 'please enter',// Please enter} export default langCopy the code

Locale /index.js creates an instance of Vuei18n and imports element-UI and its own content to be translated

import Vue from 'vue' import VueI18n from 'vue-i18n' import en from './langs/en.js' import zh from './langs/zh.js' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN' Vue.use(VueI18n) const i18n = new VueI18n({ locale: 'zh-CN', messages: { 'zh-CN': { ... zhLocale, ... zh }, 'en': { ... enLocale, ... en } } }) export default i18nCopy the code

Import the created vuei18n instance in main.js

import Vue from 'vue'
import App from './App.vue'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import i18n from './locale'

Vue.use(ElementUI, {
  i18n: (key, value) => i18n.t(key, value)
})

Vue.config.productionTip = false;

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

At this point all the preparations are done.

use

Switching internationalization Language

methods: {
  changeLocale (lang) {
    this.$i18n.locale = lang
  }
}
Copy the code

Use in template

<el-date-picker
  v-model="value1"
  type="datetime"
  :placeholder="$t('placeholder')">
</el-date-picker>
<div>
  {{ $t('title') }}
</div>
<div>
  {{ $t('title1') }}
</div>
Copy the code

Source address: https://github.com/liangtao125061github/vue-0to100-i18n.git

At the end

If you like it, please give me a like.