vue-i18n和ElementUI国际化使用总结

发布时间:2019-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue-i18n和ElementUI国际化使用总结脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

项目中需要自定义切换中/英文,基于vue.js,结合vue-i18n,ElementUI,以下是使用方法。
示例代码地址: https://github.com/lilywang71...

ElementUI国际化链接: http://element-cn.eleme.io/#/...
vue-i18n:https://github.com/kazupon/vu...
安装: npm install vue-i18n

vue.js+vue-i18n国际化

在main.js同级建i18n文件夹,并里面建i18n.js、langs文件夹,langs文件夹下建en.js、cn.js
目录如下:

.
├── App.vue
├── assets
│   └── logo.png
├── components
│   └── HelloWorld.vue
├── i18n
│   ├── i18n.js
│   └── langs
│       ├── cn.js
│       ├── en.js
│       └── index.js
├── main.js
└── store.js 
//i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './langs'

Vue.use(VueI18n)
const i18n = new VueI18n({
  locale: localStorage.lang || 'cn',
  messages
})

export default i18n
//langs/index.js

import en from './en'
import cn from './cn'
export default {
  en,
  cn
}

//en.js
const en = {
    message: {
        'hello': 'hello, world',
    }
}

export default en
//cn.js
const cn = {
    message: {
        'hello': '你好,世界',
    }
}

export default cn
//main.js

import Vue from 'vue'
import App from './App'
import store from './store'
import i18n from './i18n/i18n'
Vue.config.productionTip = false

window.app = new Vue({
  store,
  i18n,
  render: h => h(App)
}).$mount('#app')

接下来是在页面中使用、切换语言。

//html: 
<p>{{$t('message.hello')}}</p> // hello, world
//js切换语言
data() {
    return {
        lang: 'en'
    }
},
methods: {
    switchLang()  {
        this.$i18n.locale = this.lang 
    }
}

通过改变this.$i18n.locale的值就可以自动切换页面的语言了

vue.js+vue-i18n+elementUI国际化

接下来是将elementUI国际化,更改的地方不多,代码如下

//i18n.js
import Vue from 'vue'
import locale from 'element-ui/lib/locale'
import VueI18n from 'vue-i18n'
import messages from './langs'

Vue.use(VueI18n)
const i18n = new VueI18n({
  locale: localStorage.lang || 'cn',
  messages
})
locale.i18n((key, value) => i18n.t(key, value)) //重点:为了实现element插件的多语言切换

export default i18n
//en.js

import enLocale from 'element-ui/lib/locale/lang/en'
const en = {
    message: {
        'hello': 'hello, world',
    },
    ...enLocale
}

export default en
//cn.js

import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
const cn = {
    message: {
        'hello': '你好,世界',
    },
    ...zhLocale
}

export default cn

main.js保持不变,现在切换中英文,elementUI内部语言也会改变。

vue-i18n和ElementUI国际化使用总结

示例代码地址: https://github.com/lilywang71...

脚本宝典总结

以上是脚本宝典为你收集整理的vue-i18n和ElementUI国际化使用总结全部内容,希望文章能够帮你解决vue-i18n和ElementUI国际化使用总结所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue