安装

npm install vue-i18n -save

配置

  • 在src文件夹下新建locale文件夹,创建index.js,en.js,zh.js三个文件
  • 在zh,en下编写多语言
// zh.js 中文
export default {
  author: {
    name: '刘'
  }
...}

// en.js 英文
export default {
  author: {
    name: '刘'
  }
...}
  • 在index.js下配置:
import Vue from 'vue'
import VueI18n from 'vue-i18n'//引入vue-i18n
import { getLang } from '@/common/lang'//设置语言包cookie; 下面有配置
import elementEnLocale from 'element-ui/lib/locale/lang/en'//elementui英文
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'//elementui中文
import enLocale from './en'
import zhLocale from './zh'

Vue.use(VueI18n)

const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale
  },
  zh: {
    ...zhLocale,
    ...elementZhLocale
  }
}

const i18n = new VueI18n({
  locale: getLang() || 'zh',
  messages,
  silentTranslationWarn:true//取消警告
})

export default i18n
//common/lang.js
import Cookies from 'js-cookie'

const LangKey = 'lang'

function getLang() {
  return Cookies.get(LangKey)
}

function setLang(language) {
  return Cookies.set(LangKey, language)
}

function removeLang() {
  return Cookies.remove(LangKey)
}

export { getLang, setLang, removeLang }

main.js注入依赖

// main.js
import i18n from './lang'

Vue.use(ElementUI, {
  size: 'medium',
  i18n: (key, value) => i18n.t(key, value)
})

new Vue({
  el: '#app',
  router,
  store,
  i18n,
  render: (h) => h(App)
})

配置store,语言切换组件

创建lang-select.js

<template>
  <el-dropdown
    trigger="click"
    class="international-icon"
    @command="handleSetLanguage"
  >
    <div>
      <svg-icon class-name="international-icon" icon-class="language" />
    </div>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item command="zh" :disabled="language === 'zh'"
        >中文</el-dropdown-item
      >
      <el-dropdown-item command="en" :disabled="language === 'en'"
        >English</el-dropdown-item
      >
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
export default {
  name: 'LangSelect',
  computed: {
    language() {
      return this.$store.getters.language
    }
  },
  methods: {
    handleSetLanguage(lang) {
      this.$i18n.locale = lang
      this.$store.dispatch('setLanguage', lang)
    }
  }
}
</script>
<style scoped>
.international-icon {
  font-size: 20px;
  cursor: pointer;
}
</style>

store下language.js

import { getLang, setLang } from '@/common/lang'

const SET_LANG = 'SET_LANG'

const language = {
  state: {
    language: getLang() || 'zh'
  },
  mutations: {
    [SET_LANG](state, language) {
      state.language = language
      setLang(language)
    }
  },
  actions: {
    setLanguage({commit}, language) {
      commit(SET_LANG, language)
    }
  },
  getters: {
    language: state => state.language
  }
}
export default language
//记得index.js下引入language

模板中使用:{{$t()}}

https://www.cnblogs.com/zzcyeah/p/10560213.html


爬。