最近项目很多国际化的需求,语言切换时同时也需要对项目的组件自带的文字进行更新
web使用elementUI ,h5用vantUI,vantUl设置点这里
web项目设置
elementUI全部引入到项目时(也就是没有按需加载)
按需加载的i18n.js设置不同,放在第4点
1. 新建i18n.js
//enLocale 是element的语言包,需要什么就引入
//getLang是获取到缓存的值,,可以设置为store的值,只要能判别语言就可以
//利用Object.assign进行本地语言包和elementUI语言包整合
//enLocale 是element的语言包,需要什么就引入
//getLang是获取到缓存的值,,可以设置为store的值,只要能判别语言就可以
import Vue from 'vue'
import VueI18n from "vue-i18n";
Vue.use(VueI18n)
import {getLang} from "../common/cookies";
import enLocale from 'element-ui/lib/locale/lang/en'
//利用Object.assign进行本地语言包和elementUI语言包整合
let en=Object.assign(enLocale,require('@/locales/en.json'))
let zh=Object.assign(zhLocale,require('@/locales/zh.json'))
const i18n = new VueI18n({
locale: getLang() || 'en', // 语言标识
messages: {
'en': en,
'zh': zh,
}
})
export default i18n
2.main.js文件引入i18n.js
并放置全局
- 官方文件Vue.use()方法是放在i18n.js里的,但我element是直接加载在main.js里的,不想在i18n里又引一遍
import i18n from "./utils/il8n";
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value),
size: Cookies.get('size') || 'small'
})
const app = new Vue({
el: '#app',
router,
i18n,
store,
render: h => h(App)
})
3.在切换语言的页面方法设置
- 更新语言
- 更换语言缓存
- 设置i18n的语言
- 进行页面刷新,可以使用浏览器自带的reload 也可以使用app页写reload(下一个)
changeShow(val){
this.$store.commit('setVuexLang',val)
//setVuexLang进行全局更新及设置了缓存,il8n.js里的getlang()就是获取了该缓存
this.$i18n.locale=val
this.$forceUpdate()
window.location.reload();
},
3-1 App页写的reload方法
<template>
<div id="app">
<router-view v-if="isAct"/>
</div>
</template>
<script>
export default {
name: 'App',
provide(){
return {
reload:this.reload
}
},
data(){
return{
isAct:true
}
},
methods:{
reload(){
this.isAct=false
this.$nextTick(()=>{
this.isAct=true
})
}
},
watch:{
'$i18n.locale':function (val,old) {
this.reload()
},
}
}
</script>
4.按需加载elementUI设置
- i18n.js
- main.js直接使用该i18n.js即可
import Vue from 'vue'
import VueI18n from "vue-i18n";
Vue.use(VueI18n)
// import {getLang} from "../common/cookies";
import eleLocale 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 store from '../store'
let loc={
'zh':zhLocale,
'en':enLocale,
}
let en=Object.assign(enLocale,require('@/assets/lang/en.json'))
let zh=Object.assign(zhLocale,require('@/assets/lang/zh.json'))
const i18n = new VueI18n({
// locale: 'zh', // 语言标识
locale: store.getters.GET_LANG || 'zh', // 语言标识
messages: {
'en': en,
'zh': zh,
}
})
//直接引入element的方法
eleLocale.i18n ((key, value) => i18n.t(key, value))
export default i18n