小白也能学会的多语言切换

本文章实现多语言切换方式仅限于Vue,别的暂时未曾尝试!

在做后台管理的时候,经常会有要求做多语言切换功能,这个功能对于没做过的同学,咋一听之后,可能很慌!今天分享一下在Vue中实现多语言切换功能的方法。供大家参考

1、在vue中有多款插件可以实现多语言切换,本次用vue-i18n实现。首先安装

//安装vue-i18n
npm i vue-i18n -S

2、引入项目,设置全局使用

import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

3、在src文件夹中创建语言包文件夹locales(名字随意),然后创建json文件。(此文件是你想翻译的语言文件包)

//En.json
{
   "one":{
     "hello":"hello"
   }
}

//zh.json
{
   "one":{
     "hello":"你好"
   }
}

4、在main.js中创建vue-i18n实例

const i18n = new VueI18n({
  locale: 'zh',
  messages: {
    'zh': require('../src/locales/ZH.json'),
    'en': require('../src/locales/EN.json'),
  } 
})
//创建对象,导入语言包

5、在组件中注册事件,切换语言

//template
  
          
            {{$t("common.language")}}
            
          
          
            中文简体
            中文繁體
            English
          
   

// script -> methods

    // 语言切换
    langChange(command) {
      // console.log(command)
      if (command === "ZH") {
        let lang = "zh";
        this.$i18n.locale = lang;
        // console.log(this.$i18n.locale)
      }
      if (command === "EN") {
        let lang = "en";
        this.$i18n.locale = lang;
        //  console.log(this.$i18n.locale)
      }
      if (command === "BIG5") {
        let lang = "big5";
        this.$i18n.locale = lang;
        //  console.log(this.$i18n.locale)
      }

看到这里其实流程几乎走完了,还差一步点睛之笔完成这个功能,就是把语言包中的内容去替换掉显示的文字部分,这是最累的一部分没有之一。如果页面特别多!

//第一种绑定文字 
 {{$t('fileUpload.home')}}
//第二种

OK!

你可能感兴趣的:(项目经验)