The vue project uses multi-language configuration (i18n)

foreword

i18n, that is, the configuration dependency of multiple languages. Using it, it is very convenient for people from different countries to view their own projects and switch them to their own country's language.
This wave is in line with international standards [like]
Then let me tell you how to configure it

step

First, you need to install the vue-i18n plugin, use the command

npm install vue-i18n --save

Install.


Introduce the vue-i18n plugin in main.js and create an instance:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './i18n'

Vue.use(VueI18n)

const i18n = new VueI18n({
    
    
  locale: 'zh', // 默认语言
  messages, // 引入语言文件
  fallbackLocale: 'en' // 没有对应语言时的默认语言
})

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

Among them, messages is the imported language file, which is customized by us and
newly created in the project messages.js, and then follows the following format:

const messages = {
    
    
  en: {
    
    
    welcome: 'Welcome to Vue',
    home: 'Home',
    about: 'About',
    contact: 'Contact Us'
  },
  zh: {
    
    
    welcome: '欢迎使用Vue',
    home: '主页',
    about: '关于我们',
    contact: '联系我们'
  }
}

export default messages

$tIn order to use it on the page, we need to use the method in the translated place
as follows:

<template>
  <div>
    {
   
   {$t('welcome')}}
  </div>
</template>

Note: It is the attribute value we customized welcomeabovemessages.js


In addition, in order to achieve convenient language switching, you can add a drop-down box or button to the component to switch the language, and switch the language through the i18n.locale method:

<template>
  <div>
    <button @click="setLocale('en')">English</button>
    <button @click="setLocale('zh')">中文</button>
    {
   
   {$t('welcome')}}
  </div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    setLocale (locale) {
      
      
      this.$i18n.locale = locale
    }
  }
}
</script>

The above code implements adding two buttons to the component to switch languages. Language switching can be realized by calling the setLocale method when the button is clicked, and then setting the value of i18n.locale.

epilogue

The above is the process of configuring i18n for the vue project

Guess you like

Origin blog.csdn.net/xc9711/article/details/130384694