Vue I18n语言国际化

2,202 阅读1分钟

前言:

​ 近期业务需求,需要对原有项目进行国际化处理,该项目是基于Vue2+VantUI2.x的移动端H5SPA项目。上网查阅了相关资料,大多推荐使用 vue-i18n 国际化插件来实现不同语言的切换。经过测试,已基本实现中文和英文两种语言的切换。 ​ 现在主流的前端UI框架也支持语言国际化,若项目中使用UI框架比较多,建议参考UI官方文档来配置国际化。Vue I18n 通过简单的API来实现项目的国际化;该插件除了简单的翻译之外还支持数字、日期时间等本地化处理。

文档:

使用:

  • 安装插件
npm install vue-i18n
// or
yarn add vue-i18n
  • 引入插件
import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);
  • 基本设置
// 配置语言环境信息
const messages = {
  en: {
    message: {
      hello: 'hello, world!'
    }
  },
  zh: {
    message: {
      hello: '你好,世界!'
    }
  }
};

// 创建 VueI18n 实例
const i18n = new VueI18n({
  locale: 'en', // 设置地区
  messages, // 设置地区信息
});

// 创建挂载 Vue 实例
new Vue({
    router,
    i18n,
    render: h => h(App)
}).$mount("#app");

// 更改为其它的 locale
i18n.locale = 'zh';
  • 页面使用
<template>
  <div class="change_lang">
    <!-- 输入结果为:你好,世界! -->
    <h1>{{$t('message.hello')}}</h1>
  </div>
</template>

<script>
export default {
  name: 'ChangeLang',
  data () {
    return { langs: ['zh', 'en'] }
  }
}
</script>
  • 切换语言
<template>
  <div class="change_lang">
    <button @click="handleLang">中文 / EN</button>
    <br/>
    <h1>{{$t('message.hello')}}</h1>
  </div>
</template>

<script>
export default {
  name: 'ChangeLang',
  data() {
    return {
      langs: ['zh', 'en']
    }
  },
  methods:{
    handleLang() {
    	this.$i18n.locale = "zh";
    }
  }
}
</script>

:切换语言时,所有引用多语言的页面都会自动更新为对应的语言。初始化i18n实例时要设置默认展示的语言。