- 安装组件和插件
cnpm i element-ui -S // 安装element
cnpm i vue-i18n -S //安装i18n
2.在src中创建语言包
image.png
image.png
image.png
3.在main.js中引用
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from './store'
//中英文切换
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.getItem('lang')||'CH', // 语言标识
messages: {
'CH': require('./i18n/ch'), // 中文语言包
'EN': require('./i18n/en') // 英文语言包
},
})
export default i18n
Vue.config.productionTip = false;
new Vue({
router,
store,
i18n,
render: function(h) {
return h(App);
}
}).$mount("#app");
4.页面中使用$t引用
<span>{{$t('language.name')}}</span>
5.切换语言
vuex定义语言
const state={
lang:window.localStorage.getItem('lang')?window.localStorage.getItem('lang'):'CH',//CH中文 EN英文
}
const mutations = {
SET_LANG: (state, value) => {
state.lang = value;
},
}
const actions = {
changeLang({ commit }, data){
commit('SET_LANG', data)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
//页面中获取当前语言类型
computed:{
locale: {
get() {
return this.$store.state.global.lang;
},
set: function(newValue) {
this.$store.state.global.lang = newValue;
}
},
},
//点击切换语言
changeLang(){
let lang='EN'
if(this.locale=='CH'){
this.locale='EN';
}else{
this.locale='CH';
}
this.$store.dispatch('global/changeLang', this.locale);
this.$i18n.locale=this.locale;
window.localStorage.setItem("lang", this.locale);
},
网友评论