在Vue中加入國際化(i18n)中英文功能

1.npm安裝方法vue

npm install vue-i18n --save

2.在src資源文件下建立文件夾i18n,i18n下面建立index.js文件,引入VueI18n和導入語言包(按開發需求可添加多種語言)npm

具體代碼:json

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

Vue.use(VueI18n)
 
// 註冊i18n實例並引入語言文件
const i18n = new VueI18n({
  locale: 'zh_cn',
  messages: {
    'zh_cn': require('@/assets/languages/zh_cn.json'),
    'en_us': require('@/assets/languages/en_us.json')
  }
})

export default i18n

3.在mian.js文件中:app

import i18n from './i18n';

new Vue({
  el: '#app',
 i18n,
  router,
  store,
  components: { App },
  template: '<App/>'
})

4.接在assets文件下新建languages包:ui

語言JSON包:this

//zh_cn.json
{
  "SYS": {
    "confirmButtonText": "確認",
    "cancelButtonText": "取消"
  },
  "user": {
    "title": "我的中心",
    "Exit": "退出系統",
    "Processing": "代辦工做",
    "initiated": "我發起的",
    "transferring": "辦結工做",
    "phoneService": "電話客服",
    "Accounts": "帳號中心",
    "modifyPassword": "修改密碼",
    "Language": "切換中英文",
    "about": "關於",
    "confirmExit": "肯定退出?",
    "confirmChangeLanguage": "是否切換語言?",
    "ScExit": "退出成功",
    "loadingtext": "退出帳號中..."
  }
}
//en_us.json

{
"SYS": { "confirmButtonText": "Comfirm", "cancelButtonText": "Cancel" }, "user": { "title": "Personal center", "Exit": "Exit system", "Processing": "to-do list", "initiated": "I initiated", "transferring": "transferring work", "phoneService": "Telephone customer service", "Accounts": "Account center", "modifyPassword": "change Password", "Language": "CH/EN", "about": "about", "confirmExit":"Confirm Exit ?", "confirmChangeLanguage":"Whether to switch languages", "ScExit":"exit successfully", "loadingtext":"Exiting..." } }

5.組件使用(語言切換)spa

        <van-cell
          icon="setting-o"
          @click="changeLanguage"
          :title="$t('user.Language')"
          :value="Languagevalue"
          is-link
        />

   展現語言切換彈窗:(注意必定要使用$t())code

    //選擇語言
    changeLanguage() {
      this.$dialog
        .confirm({
          message: this.$t("user.confirmChangeLanguage"),
          confirmButtonText: this.$t("SYS.confirmButtonText"),
          cancelButtonText: this.$t("SYS.cancelButtonText")
        })
        .then(() => {
          this.Language = !this.Language;
          if (this.Language == false) {
            this.CHLanguage("zh_cn");
            this.Languagevalue = "English";
          } else {
            this.CHLanguage("en_us");
            this.Languagevalue = "Chinese";
          }
        });
    },
    // 語言切換
    CHLanguage(lang) {
      lang === "" ? "zh_cn" : lang;
      this.$i18n.locale = lang;
    },

 

效果:component

 

 

相關文章
相關標籤/搜索