使用vue-i18n为vue添加多语言支持

前言

最近项目因为国际化原因使用到了多语言,因为前端是使用vue的,后端同学就没有办法帮忙做了,而我们的vue又没有使用服务端渲染,值得庆幸的,我们的vue生态是良好的,我找到了vue-i18n来做多语言的适配。

vue中添加多语言
  1. 首先我们在项目中添加vue-i18n的依赖包
npm install vue-i18n --save
  1. 然后在我们的项目中的src文件夹下面添加locales文件夹,然后在文件夹中新建我们的json格式的语言包,还有index.js文件;目录大致为:
  ···
- src
  |- locales
     |- en.json
     |- zh.json
     |- index.js
  ···
  1. 在我们语言包中写入相应的文字
- en.json
{
  "message": {
    "hello": "hello world"
  }
}
- zh.json
{
  "message": {
    "hello": "你好世界"
  }
}
  1. index.js中引入vue-i18n
- index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const DEFAULT_LANG = 'zh'
const LOCALE_KEY = 'localeLanguage'

const locales = {
  zh: require('./zh.json'),
  en: require('./en.json'),
}
const i18n = new VueI18n({
  locale: DEFAULT_LANG,
  messages: locales,
})
//这里我们抛出一个setup方法,用来修改我们的语言;
//并且在这个方法中,我们把用户选择的语言存储在localStorage里面,方便用户下次进入是直接使用上次选择的语言
//因为语言的不同,可能我们页面上的样式也会有相应的调整,所以这里在body上加入了相应的类名,方便我们做样式定制
export const setup = lang => {
  if (lang === undefined) {
    lang = window.localStorage.getItem(LOCALE_KEY)
    if (locales[lang] === undefined) {
      lang = DEFAULT_LANG
    }
  }
  window.localStorage.setItem(LOCALE_KEY, lang)

  Object.keys(locales).forEach(lang => {
    document.body.classList.remove(`lang-${lang}`)
  })
  document.body.classList.add(`lang-${lang}`)
  document.body.setAttribute('lang', lang)
//把当前语言设置到vue的配置里面,方便在代码中读取
  Vue.config.lang = lang
  i18n.locale = lang
}
//设置默认语言为中文
setup('zh')
//把i18n绑定到window上,方便我们在vue以外的文件使用语言包
window.i18n = i18n;
export default i18n
  1. main.js中把vue-i18n注入到vue
- main.js
//注意,因为我们index.js中把i18n绑定到了window,所以要在第一个引入
import i18n from './locales'
import Vue from 'vue'
import App from './App.vue'
import './common.scss'

const app = new Vue({
  components: {
    App
  },
  i18n,
  render: h => h(App),
});
  1. 使用语言包
  • vue模板中,我们直接使用$t("message.hello")来获取语言包变量;
  • vuejs中我们使用this.$i18n.t("message.hello")或者i18n.t("message.hello")来获取语言包变量;
  • vue以外的js中,我们可以使用i18n.t("message.hello")来获取语言包变量;
- HelloWorld.vue
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h3>{{$t("message.hello")}}</h3>
    <a @click="change('en')">英文</a>
    <a @click="change('zh')">中文</a>
  </div>
</template>
<script>
import { setup } from "./../locales/index.js";
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  mounted (){
    let h = this.$i18n.t("message.hello") ;
    let hh = i18n.t("message.hello")
    console.log(h,hh);
  },
  methods:{
    change (language){
      setup(language)
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
  margin: 0 20px;
  cursor: pointer;
}
</style>

自此,我们就可以在项目中愉快的使用多语言了。

在单独文件中使用,待更新

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章