[vue+vue-i18n plug-in] Realize the Chinese and English switching of the vue project

To understand a plug-in, it is very important to read the document. Please click here for
the document address and jump to the official Vue I18n document

When the Vue project needs to switch between Chinese and English, it can be realized with the help of plug-ins, and there is no difficult technology

1. Installation

npm install vue-i18n

2. Global import, introduced in main.js

import Vue from 'vue'   //一般main.js中都有这一行
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'   //导入element-ui的英文文件
import cnLocale from 'element-ui/lib/locale/lang/zh-CN'  //导入element-ui的中文文件
Vue.use(VueI18n)
const i18n=new VueI18n({
    
    
    locale:localStorage.getItem('languageSet')||'zh',  
     //从localStorage里获取用户中英文选择,
    没有则默认中文,一定要有默认语言,
    不然新设备访问的时候,localStorage中没有值就会出现bug
    messages:{
    
    
        'zh': {
    
    
          ...require('./components/lang/zh'),
          ...cnLocale
        },
        'en': {
    
    
          ...require('./components/lang/en'),
          ...enLocale
        }
    }
})
//element官方方法 //为了实现element插件的多语言切换
Vue.use(Element, {
    
    
  size: Cookies.get('size') || 'medium', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value),
})
new Vue({
    
    
  el: '#app',
  router,
  store,
  i18n,
  render: h => h(App),
})

3. Create a new lang folder under the src directory, write the data that needs to be changed in the zh.js and en.js files, the zh.js and en.js content, the key must correspond, and you can directly use the js definition on the page data
-en.js

export default {
    
    
  role: {
    
    
    roleCode: 'RoleCode',
    roleName: 'RoleName',
    createDate: 'CreateDate',
    roleType: 'RoleType',
    roleDesc: 'RoleDesc'
  }
}

zh.js

export default {
    
    
  role: {
    
    
    roleCode: '角色编码',
    roleName: '角色名称',
    createDate: '创建时间',
    roleType: '角色类型',
    roleDesc: '角色描述',
   
  },
 
}

**

ps: index.js is not used, so don’t consider it, it’s just for your own review

**
insert image description here

index.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
//引入element 自带的语言包
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import elementEsLocale from 'element-ui/lib/locale/lang/es'// element-ui lang
//引入自己创建的语言包
import enLocale from './en'
import zhLocale from './zh'
import esLocale from './es'

Vue.use(VueI18n)

const messages = {
    
    
  en: {
    
    
    ...enLocale,
    ...elementEnLocale
  },
  zh: {
    
    
    ...zhLocale,
    ...elementZhLocale
  },
  es: {
    
    
    ...esLocale,
    ...elementEsLocale
  }
}
export function getLanguage() {
    
    
  const chooseLanguage = Cookies.get('language')
  if (chooseLanguage) return chooseLanguage

  // if has not choose language
  const language = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    
    
    if (language.indexOf(locale) > -1) {
    
    
      return locale
    }
  }
  return 'en'
}
const i18n = new VueI18n({
    
    
  // set locale
  // options: en | zh | es
  locale: getLanguage(),
  // set locale messages
  messages
})

export default i18n

Fourth, start using the page

      <div class="switchLag">
        <svg-icon class="switchIcon" v-show="language == 'en_US'" class-name="英文" icon-class="英文" @click="changeLage('en')"></svg-icon>
        <svg-icon class="switchIcon" v-show="language == 'zh_CN'" class-name="中文" icon-class="中文" @click="changeLage('zh')"></svg-icon>
      </div>  

.switchLag {
    
    
  .switchIcon {
    
    
    margin-top: 10px;
    width: 30px;
    height: 30px;
    cursor: pointer;
  }
}


  language: this.$store.state.user.language,

i18n is the instance object of the VueI18n variable in main.js
locale is the default language set by i18n
zh en is the set language variable

  // 中英文切换
    changeLage(v) {
    
    
      if (v == 'en') {
    
    
        this.$i18n.locale = 'zh'
        //因为切换语言的关系,可以将语言标识保存在localStorage中,
        记得一点就是一定要有默认语言,不然新设备访问的时候,localStorage中没有值就会出现bug
        localStorage.setItem('languageSet', this.$i18n.locale)
        this.language = 'C'
      } else {
    
    
        this.language = 'E'
        this.$i18n.locale = 'en'
        localStorage.setItem('languageSet', this.$i18n.locale)
      }
      const data = {
    
    
        userId: xxx.userId,
        language: this.language,
        userName: xxx.name,
        nickName: xxx.nickName,
        // 中英文(中文C  英文N)
      }
      setLanguage(data).then(res => {
    
        
      this.language = res.data.language
      })
   
    },

5. Use the data defined in en.js

            <el-input
              v-model="modelName"
              :placeholder="$t('flowModel.name')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 10px"
              class="filter-item"
           
            >
            </el-input>
          <el-table-column :label="$t('role.id')" prop="id" 
          align="center">
            <template slot-scope="scope">
              <span>{
    
    {
    
     scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('role.roleCode')" prop="roleCode" 
          align="center">
            <template slot-scope="scope">
              <span>{
    
    {
    
     scope.row.roleCode}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('role.RoleName')" prop="RoleName" 
          align="center" width="160">
            <template slot-scope="scope">
              <span>{
    
    {
    
     scope.row.RoleName}}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('role.createDate')" prop="createDate" 
          align="center">
            <template slot-scope="scope">
              <span>{
    
    {
    
     getNickName(scope.row.createDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('role.roleDesc')" prop="roleDesc" 
          align="center">
            <template slot-scope="scope">
              <span>{
    
    {
    
     scope.row.roleDesc }}</span>
            </template>
          </el-table-column>

6. Regarding language: this.$store.state.user.language, the value of language should be stored in vuex, and after each login to obtain user information, the value of language should be taken from it

state:{
    
    
    language:''

},
mutations:{
    
    
    SET_LANGUAGE: (state, name) => {
    
    
      state.language = name
    },
},
actions:{
    
    
   // 获取用户信息
    GetInfo({
    
     commit, state }) {
    
    
      return new Promise((resolve, reject) => {
    
    
        getInfo(state.token)
          .then(res => {
    
     
   const user = res.user
       commit('SET_LANGUAGE', user.language)
 })
          .catch(error => {
    
    
            reject(error)
          })
      })
    },

}

Guess you like

Origin blog.csdn.net/weixin_49668076/article/details/128198620