vue使用vue-i18n结合vant移动端组件实现国际化

1.安装vue-i18n

npm i vue-i18n -S

2.设置语言的配置文件

在src下面创建locale文件夹,创建英文与中文的配置文件en.js与zh.js

// 这两个语言的资源文件根据项目的需求自行进行其中内容的配置
// src/locale/en.js
const message = {
  message: {
    hello: 'hello world'
  },
  footer: ['home', 'catgory', 'cart', 'users'],
  userEdit: ['nickname', 'sex', 'birthday', 'tel', 'address', 'loginOut']
}
module.exports = message


// src/locale/zh.js
const messages = {
  message: {
    hello: '你好世界'
  },
  footer: ['首页', '分类', '购物车', '个人中心'],
  userEdit: ['昵称', '性别', '出生日期', '电话', '地址管理', '退出登录']
}
module.exports = messages

// src/locale/index.js
// 在vue中使用i18n并生成他的实例,实例中根据语言地区的不同,去配置不同的地区信息
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
  locale: localStorage.getItem('lang') || 'en', // 设置地区
  messages: {
    en: require('./en'),
    zh: require('./zh')
  }// 设置地区信息
})
export default i18n

// 在vue中应用国际化的流程
// 在入口文件main.js中引用
import i18n from './locale'
new Vue({
  i18n,
  router,
  store,
  render: h => h(App)
}).$mount('#app')

// 这里举例locale配置信息的结构,下面列出使用的方式
{
  "en": {  // 'en' Locale
    "key1": "this is message1", // 基本的
    "nested": { // 嵌套
      "message1": "this is nested message1"
    },
    "errors": [ // 数组
      "this is 0 error code message",
      {  // 数组嵌套对象
        "internal1": "this is internal 1 error message"
      },
      [  // 数组嵌套数组
        "this is nested array error 1"
      ]
    ]
  },
  "ja": { // 'ja' Locale
    // ...
  }
}
// 基于以上的locale配置,我们可以用以下的方式进行翻译
  <!-- 基本的 -->
  <p>{{ $t('key1') }}</p>
  <!-- 嵌套 -->
  <p>{{ $t('nested.message1') }}</p>
  <!-- 数组 -->
  <p>{{ $t('errors[0]') }}</p>
  <!-- 数组嵌套对象 -->
  <p>{{ $t('errors[1].internal1') }}</p>
  <!-- 数组嵌套数组 -->
  <p>{{ $t('errors[2][0]') }}</p>

// 在vue项目中,资源的正式使用方式为
// 1.在标签中使用,使用双大括号包裹
<p>{{ $t("message.hello") }}</p>
// 2.在属性中使用,使用绑定属性
<van-cell :title="$t('userEdit[5]')" />
// 3.js中使用,可以直接使用this
console.log(this.$t('userEdit[3]'))

// 在app中我们如何根据用户的选择来进行语言的切换呢?
// 我们可以根据用户的选择将语言环境存放在localstorage中,我们在创建i18n实例的时候可以通过localstorage去获取,同时也可以设置默认的语言具体可以查看上面的src/locale/index.js中的内容
 <van-dropdown-menu>
    <van-dropdown-item v-model="value1" :options="option1" @change="changeLang" />
 </van-dropdown-menu>
// 切换语言
 changeLang () {
   localStorage.setItem('lang', this.value1)
 }

效果图:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值