vue 国际化 vue-i18n 双语言 语言包

这篇博客介绍了如何使用vue-i18n进行国际化设置,包括安装插件、配置默认语言和语言包,以及在模板中使用翻译。同时展示了中/English切换功能的实现,通过配置不同语言环境来改变组件如Toast的提示语。

1.安装vue-i18n

2.在main.js里面引用

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

3.实例化i18n,并配置默认的语言模式,以及对应的文件(也是在main.js里使用)

如下。cn 中文包对应的是cn.js

en 对应的是英文 en.js 包

const i18n = new VueI18n({
  //定义默认语言
  locale: 'cn', 
  messages:{
    'cn': require('./common/lang/cn'),
    'en': require('./common/lang/en')
  }
})

4.cn.js 怎么写?

module.exports = {
    placeholder: {
        phone: '手机号',
        input_code: '输入验证码',
        passwordSix: '请输入6到18位密码'
    },
    sidebar: {
        MyAccount: '账户信息',
        PersonalInformation: '个人信息',
        Message: '我的消息',
        MyWallet: '我的钱包',
        MyProject: '我的方案'
    },
    home: {
       SendCode: 'Send verification code success'   
    }
}

当然 en.js 也需要配置一份

module.exports = {
    placeholder: {
        phone: 'Phone Number',
        input_code: 'Verification code',
        passwordSix: 'Please enter 6 to 18 Bit passwords'
    },
    sidebar: {
        MyAccount: 'My Account',
        PersonalInformation: 'Personal Information',
        Message: 'Message',
        MyWallet: 'My Wallet',
        MyProject: 'My Project'
    },
    home: {
       SendCode: 'send Code Success功'   
    }
}

5.如何在template中使用?

需要这样渲染出来

{{ $t("sidebar.MyWallet") }}

<li>{{ $t("sidebar.MyWallet") }}</li>

当然placeholder也是可以通过他来更改的。

<input type="text" v-model="phoneNumber" :placeholder="$t('placeholder.phone')"> 对应好配置好的placeholder就行。

中/English 切换函数

tag () {
    if (this.$i18n.locale === 'en') {
        this.$i18n.locale = 'cn'
    } else {
        this.$i18n.locale = 'en'
    }    
}

在js里如何拿配置过的语言来使用?

this.$t("sidebar.MyAccount")

这里我们使用了mint-ui框架中的Toast消息提示框,想让它根据语言环境来显示不同的提示语。

双语言前

Toast({message: '验证码发送成功'})

更改为双语言后

Toast({message: this.$t("home.SendCode")})

搞定!

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值