1.安装vue-i18n(切记:vue2x的版本,一定要安装8.9.0以下的版本)
npm install vue-i18n@8.9.0 --save
2.在src中,新建lang文件
--src
+ lang
+ index.js
+ en_us.js
+ zh_cn.js
3.index.js
import Vue from 'vue'
import Element from 'element-ui'
import VueI18n from 'vue-i18n'
import locale from 'element-ui/lib/locale'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from './en_us'
import zhLocale from './zh_cn'
import Cookies from 'js-cookie'
Vue.use(VueI18n)
const messages = {
zh: {
language: '简体中文',
...enLocale,
...zhLocale
},
en: {
language: 'English',
...enLocale ,
...enLocale
}
}
const i18n = new VueI18n({
locale: Cookies.get('language') || 'en', // set locale
messages // set locale messages
})
locale.use(Element, {
i18n: (key, value) => i18n.t(key, value)
})
// 导出messages 给切换语言的时候用
export { i18n, messages }
4.zh_cn.js文件
export default {
test: '测试',
tabel: {
label: '中文'
}
}
5.en_us文件
export default {
test: 'Test',
tabel: {
label: 'Chinese'
}
}
// zh_cn与 en_us的key值需要保持一致
6.main.js
import Vue from 'vue'
import Cookies from 'js-cookie'
import 'normalize.css/normalize.css'
import Element from 'element-ui'
import App from './App'
import store from './store'
import router from './router/routers'
import { i18n } from '@/lang'
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value), // 这里会根据选的语言切换Element-ui的语言
size: Cookies.get('size') || 'small' // set element-ui default size
})
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
i18n,
store,
render: h => h(App)
})
7.如何使用及切换语言,比如在App.vue上进行多语言的切换
<template>
<div id="app">
<p>{{ $t('test')}}</p>
<p>{{$t('tabel.label')}}</p>
<el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click" @command="choose">
<span class="language">{{ language }}<i class="el-icon-caret-bottom" /></span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item v-for="(item, key ,i) in messages" :key="i" :command="key">{{ item.language }}</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<router-view />
</div>
</template>
<script>
import { messages } from '@/lang'
export default {
name: 'App',
data() {
return {
messages: messages,
language: '',
test: this.$t('test') // 如果在非temlate模版中取多语言的值的话,去使用this.$t('xxx')
}
},
created() {
this.setLanguage()
},
methods: {
setLanguage() {
const lang = Cookies.get('language') || 'en'
this.language = this.messages[lang].language
},
choose(lang) {
this.$i18n.locale = lang
Cookies.set('language', lang)
this.setLanguage()
}
}
}
</script>
|