在Vue中加入国际化(i18n)中英文功能

1.npm安装方法

npm install vue-i18n --save

2.在src资源文件下创建文件夹i18n,i18n下面创建index.js文件,引入VueI18n和导入语言包(按开发需求可添加多种语言)

具体代码:

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文件中:

import i18n from './i18n';

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

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

语言JSON包:

//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.组件使用(语言切换)

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

   展示语言切换弹窗:(注意一定要使用$t())

    //选择语言
    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;
    },

 

效果:

 

 

 

转载于:https://www.cnblogs.com/lwming/p/11280943.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值