Preface:

Recent business needs require the internationalization of the original project, which is a mobile H5SPA project based on Vue2+ VanTUi2.x. I have looked up relevant information online, and most of them recommend the use of VUE-I18N internationalization plug-in to achieve the switch of different languages. After testing, the switch between Chinese and English has been basically realized. Currently, the mainstream front-end UI framework also supports language internationalization. If the UI framework is widely used in the project, it is recommended to refer to the official UI document to configure internationalization. Vue I18n implements project internationalization through a simple API; In addition to simple translation, the plugin also supports localization of numbers, dates and times.

Documents:

  • Vue-i18n 【github address 】
  • Vue I18n【 英 文 版 】
  • Vue I18n

Use:

  • Installing a plug-in
npm install vue-i18n
// or
yarn add vue-i18n
Copy the code
  • The introduction of the plugin
import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);
Copy the code
  • Basic setup
// Set the locale information
const messages = {
  en: {
    message: {
      hello: 'hello, world! '}},zh: {
    message: {
      hello: 'Hello world! '}}};// Create a VueI18n instance
const i18n = new VueI18n({
  locale: 'en'.// Set the locale
  messages, // Set the region information
});

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

// Change to another locale
i18n.locale = 'zh';
Copy the code
  • Page using
<template>
  <div class="change_lang">
    <! Enter the result: Hello, world! -->
    <h1>{{$t('message.hello')}}</h1>
  </div>
</template>

<script>
export default {
  name: 'ChangeLang',
  data () {
    return { langs: ['zh'.'en']}}}</script>
Copy the code
  • To switch between languages
<template>
  <div class="change_lang">
    <button @click="handleLang">Chinese/EN</button>
    <br/>
    <h1>{{$t('message.hello')}}</h1>
  </div>
</template>

<script>
export default {
  name: 'ChangeLang'.data() {
    return {
      langs: ['zh'.'en']}},methods: {handleLang() {
    	this.$i18n.locale = "zh"; }}}</script>
Copy the code

Note: When switching languages, all pages referencing multiple languages are automatically updated to the corresponding language. The default language to display is set when initializing i18N instances.