前言

多语言,一听很高大上,象征着与国际接轨,中文版(简体、繁体)、英文版、日文版等等。感觉6b的不要不要的,下面来看看vue怎么来实现这个操作了?(其实很简单)

vue多语言插件vue-i18n使用介绍

详细步骤

安装vue-i18n

npm install vue-i18n -S

引入

在main.js中引入vue-i18n

import VueI18n from 'vue-i18n' Vue.use(VueI18n)

定义语言文件

const messages = { //简体中文 cn: { message: { hello: '你好', author: '龙的传人' } }, //英文 en: { message: { hello: 'Hello', author: 'Chinese' } }, // 繁体中文 tw: { message: { hello: '你好', author: '龍的傳人' } } }

vue-i18n初始化

const i18n = new VueI18n({ locale: 'cn', // 默认语言 messages })

vue-i18n挂载到vue实例

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

vue模板文件中使用

<h1>{{ $t("message.hello") }}</h1>

js中使用

computed:{ hello(){ return this.$t("message.hello") + this.$t("message.author"); } }

切换语言

this.$i18n.locale = 'en' // 切换英文

单独定义语言文件 并加载到vue-i18n初始化中

// cn.js export default { message: { hello: '你好', author: '龙的传人' } }
// en.js export default { message: { hello: 'Hello', author: 'Chinese' } }
import cnlang from './lang/cn.js' import enlang from './lang/en.js' const i18n = new VueI18n({ locale: 'cn', // 默认语言 messages: { 'cn': cnlang, 'en': enlang } })