美文网首页vue~i18n的使用
vue+elementUI的国际化

vue+elementUI的国际化

作者: 陶菇凉 | 来源:发表于2021-11-22 14:31 被阅读0次
  1. 安装组件和插件
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);
   },

相关文章

网友评论

    本文标题:vue+elementUI的国际化

    本文链接:https://www.haomeiwen.com/subject/talbtrtx.html