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


先不使用ElementUI,就简单的vue.js+vue-i18n使用方法:

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



il8n.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))
export default i18n

index.js

import en from './en' // 英语
import cn from './cn' // 中文
export default {
  en: en,
  cn: cn
}

cn.js

import enLocale from 'element-ui/lib/locale/lang/zh-CN'
const cn = {
  login: {
    btn: '登录'
  },
  ...enLocale
}
export default cn

en.js

import enLocale from 'element-ui/lib/locale/lang/en'
const en = {
  login: {
    'btn': 'Login'
  },
  ...enLocale
}
export default en

然后在main.js中加入

import i18n from './il8n/il8n'
new Vue({
  el: '#app',
  router,
  i18n,
  store,
  components: { App },
  template: '<App/>'
})

然后封装一个切换语言的组件

<template>
  <el-dropdown trigger="click" class='international' @command="handleSetLanguage">
    <div>
      <span class="el-dropdown-link">{{language}}<i class="el-icon-arrow-down el-icon--right"></i>
    </span>
    </div>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="cn">中文</el-dropdown-item>
      <el-dropdown-item command="en">English</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
export default {
  data () {
    return {
      language: ''
    }
  },
  mounted () {
    const _lang = localStorage.lang || 'cn'
    this.getLanguage(_lang)
  },
  methods: {
    handleSetLanguage (lang) {
      this.$i18n.locale = lang
      localStorage.setItem('lang', lang)
      this.getLanguage(lang)
    },
    getLanguage (val) {
      if (val === 'cn') {
        this.language = '中文'
      }
      if (val === 'en') {
        this.language = 'English'
      }
    }
  }
}
</script>
<style>
  .international .el-dropdown-link {  cursor: pointer;  color: #c0ccda;  font-size: 14px;  }
  .el-icon-arrow-down {  font-size: 14px;  }
</style>
<style scoped>
  .international-icon {
    font-size: 20px;
    cursor: pointer;
    vertical-align: -5px !important;
  }
</style>

接下来在页面中使用:

<template>
  <div>
  <LangSelect></LangSelect>
  <el-button type="primary">{{$t('login.btn')}}</el-button>
  </div>
</template>
<script>
import LangSelect from '@/components/home/LangSelect'
export default {
  components: { LangSelect },
  data () {},
  mounted () {},
  methods: {}
}
</script>
Logo

前往低代码交流专区

更多推荐