current position:Home>Use of I18N in Vue

Use of I18N in Vue

2022-04-29 17:56:19Qingyi Liuyang

Introduce Vue I18n yes Vue.js International plug-ins for . It can easily integrate some localization functions into your Vue.js In the application .
1、 Install... In the project i18n

npm install vue-i18n

2、 If you use it in a modular system , You have to pass Vue.use() Explicitly install vue-i18n:

import Vue from 'vue' 
import VueI18n from 'vue-i18n'  

Use in projects
In our project, the most is to switch the display of language through label switching ,
locale Is the configuration that controls the display language

Here is the complete code
Folder path
 Insert picture description here

establish i18n Put the folder in the language and index.js file
index Code

import VueI18n from 'vue-i18n'
import Vue from 'vue'

// introduce element Language pack 
import localeLib from 'element-ui/lib/locale'  // Local 
import enLocale from "element-ui/lib/locale/lang/en"; // english 
import zhLocale from "element-ui/lib/locale/lang/zh-CN";  // chinese 

//  The introduction of language packs is also required js file ,export default Object that throws the language pack 
import en from './lang/saas-en.json'
import zh from'./lang/saas-zh-CN.json'


// Get the locally selected language 
var lang =
  Cookie.get("bx_user_lang") ||
  navigator.language ||
  navigator.userLanguage ||
const i18n = new VueI18n({
  locale: lang, //  Language mark 
  fallbackLocale: 'zh-CN',
  messages: {
    en: Object.assign(en, enLocale),
    "zh-CN": Object.assign(zh, zhLocale)
//  Setup language 
localeLib.i18n((key, value) => i18n.t(key, value))
export default i18n


import i18n from './i18n/i18n'; 
/* eslint-disable no-new */
new Vue({
    el: '#app',
    i18n, // Very important , Don't forget 
    components: {
     App },
    template: '<App/>'

Use... In components

   {$t('message.text')}}</span> // Usage mode 1
   {title}}</p> // Usage mode 3
        <span v-text="$t('message.text')"></span>// Usage mode 2
        <el-select @change="langChange" placeholder=" Please choose a language ">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
<script> export default {
       data () {
       return {
       title:this.$t('message.text'), options:[ {
       value: 'cn', label: ' chinese ' }, {
       value: 'en', label: 'English' } ] } }, methods: {
       // Language switching  langChange(e){
       localStorage.setItem('lang',e); this.$i18n.locale = e; window.location.reload() } } } </script>

Finally, attach the address of the official document

copyright notice
author[Qingyi Liuyang],Please bring the original link to reprint, thank you.

Random recommended