Vue internationalization (vue-i18n)

1. Installation

Three ways:

1. Script introduction

<script src="https://unpkg.com/vue/dist/vue.js"></script> 

 <script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

2. npm installation

 npm install vue-i18n

3. yarn installation

 yarn add vue-i18n

Two, configuration

main.js file configuration

1. Introduce the i18n internationalization plug-in

import Vue from 'vue'

import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

2. Register the i18n instance and import language files, file formats, etc. to analyze

const i18n = new VueI18n({ 

 locale: 'zh', // 定义默认语言为中文 

 messages: {   

    'zh': require('@/assets/languages/zh.json'),   

    'en': require('@/assets/languages/en.json') 

  }

});

3. Inject i18n into the vue instance

new Vue({

   el: '#app',

   router,

   i18n,

   components: { App},

   template: '<App/>'

 }); 

4. File format (json file)

First look at the zh.json file, as follows:

insert image description here

The corresponding en.json format is the same as zh.json, just change Chinese to English, as follows:

insert image description here

3. Template rendering
html files need to add { {}}

   {
   
   {$t('common.home')}}

js file

   $t('common.home')

Click to switch languages, as follows:
insert image description here
(Note: github address: Avery_G)

Blog migrated to GitHub

Guess you like

Origin blog.csdn.net/gladysdrea/article/details/107090048