vue项目中实现多语言(i18n)

1、安装

npm install i18n

2、在main.js中引入

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

// 多语言实例
const i18n = new VueI18n({
  locale: (function () {
    if (localStorage.getItem('lang')) {
      return localStorage.getItem('lang')
    }
    return 'zh'
  }()),
  messages: {
    'zh': require('./assets/i18n/zh'),   // 中文语言包
    'en': require('./assets/i18n/en')    // 英文语言包 
  }
})

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

引入这些都没什么好说的,主要是多语言实例,因为切换语言的关系 ,我将语言标识保存在了 localStorage 中,这里记得一点就是一定要有默认语言,不然新设备访问的时候localStorage中没有值就会出现BUG。

3、建立语言包

语言包只要放在src下即可,这里我只用到了中文和英语。然后语言包在main.js中引入,上面main.js中我已经写了

messages: {
    'zh': require('./assets/i18n/zh'),   // 中文语言包
    'en': require('./assets/i18n/en')    // 英文语言包 
  }

然后我们在看一下语言包的里面怎么写

其实只需要将对应的键值对写好在 module.exports 导出即可使用

4、使用

1、在标签中使用

<div class="register_heds">{{$t("login.title")}}</div>

2、在input 的 placeholder 中使用,其实就是vue的 v-bind

<input type="password" :placeholder="$t('login.password')" maxlength="24" v-model="log_password">

3、在JS中使用

this.$t('login.clause')

4、语言切换方法

Language(){
            if(this.$i18n.locale === 'zh'){
                this.$i18n.locale = 'en'
                localStorage.setItem('lang','en')
            }else{
                this.$i18n.locale = 'zh'
                localStorage.setItem('lang','zh')
            }
        }

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值