vue实现国际化(i18n)

此篇文章主要是针对在vue中通过vue-i18n实现国际化

1.安装

npm

npm install --save vue-i18n

yarn

yarn add vue-i18n

2.在项目中创建一个lang文件夹

3.在en.js和zh.js分别写入对应的字段,例子如下:
en.js

export default {
  message:{
    homePage:'Home Page'
  }
}

zh.js

export default {
  message:{
    homePage:'首页'
  }
}

index.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zhLocale from './zh'
import enLocale from './en'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'zh', //默认显示语言
  messages: {
    zh: {
      ...zhLocale,
    },
    en: {
      ...enLocale,
    }
  }
})

export default i18n

4.main.js中引入

5.使用

<template>
  <div>
    <span>{{$t('message.homePage')}}</span>
    <button @click="changeLang">切换</button>
  </div>
</template>

<script>
export default {
  methods: {
    changeLang() {
      let lang = this.$i18n.locale
      this.$i18n.locale = lang == 'zh' ? 'en' : 'zh'
    }
  }
}
</script>

<style>
</style>
原文地址:https://www.cnblogs.com/AdolphWilliam/p/14600697.html