vue项目的国际化实现方案

1、安装依赖vue-i18n

npm i vue-i18n -S

2、配置main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
// 引入国际化插件
import VueI18n from 'vue-i18n'

Vue.use(VueI18n) // 通过插件的形式挂载

const i18n = new VueI18n({
  locale: 'zh-CN', // 语言标识
  // this.$i18n.locale // 通过切换locale的值来实现语言切换
  messages: {
    'zh-CN': require('./locales/zh'), // 中文语言包
    'en-US': require('./locales/en') // 英文语言包
  }
})

/* eslint-disable no-new */
// 把vue实例挂载在window.vm,方便使用vue的实例
window.vm = new Vue({
  el: '#app',
  router,
  store,
  i18n, // 国际化
  components: {
    App
  },
  template: '<App/>'
})

3、配置语言包

创建locales文件夹,文件夹中创建zh.js和en.js

zh.js

export const lang = {
  Home: {
    'title': '首页',
    'submit': '提交'
  },
  Mall: {
    'shoppingCart': '购物车',
    'detail': '详情'
  }
}

en.js

export const lang = {
  Home: {
    'title': 'Home',
    'submit': 'Submit'
  },
  Mall: {
    'shoppingCart': 'ShoppingCart',
    'detail': 'Detail'
  }
}

4、组件中使用

<template>
  <div class="hello">
    <div>{{$t('lang.Home.submit')}}</div>
    <div @click="switchLangCh">切换中文</div>
    <div @click="switchLangEn">切换英文</div>
  </div>
</template>

<script>
export default {
  name: 'I18nTest',
  components: {
  },
  data () {
    return {
      value: 'Welcome to Your Vue.js App'
    }
  },

  created () {
  },

  methods: {
    switchLangCh () {
      this.$i18n.locale = 'zh-CN' // 切换成中文
    },
    switchLangEn () {
      this.$i18n.locale = 'en-US' // 切换成英文
    }
  }
}
</script>

<style lang="less" scoped>
</style>

5、App.vue监听语言环境并切换国际化

<template>
  <div id="app">
    <!-- <keep-alive> -->
    <router-view />
    <!-- </keep-alive> -->
  </div>
</template>
<script>

export default {
  name: 'App',
  created () {
    this.switchI18n()
  },
  methods: {
    switchI18n () {
      // 判断当前环境是中文还是英文
      const nowLang = navigator.language || navigator.browserLanguage
      if (nowLang.indexOf('zh') > -1) {
        this.$i18n.locale = 'zh-CN' // 切换国际化成中文
      } else {
        this.$i18n.locale = 'en-US' // 切换国际化成英文
      }
    },
  }
}
</script>
<style>
</style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值