vue项目的国际化实现方案
1、安装依赖vue-i18n
npm i vue-i18n -S
2、配置main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
// 引入国际化插件
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) // 通过插件的形式挂载
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
// this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {
'zh-CN': require('./locales/zh'), // 中文语言包
'en-US': require('./locales/en') // 英文语言包
}
})
/* eslint-disable no-new */
// 把vue实例挂载在window.vm,方便使用vue的实例
window.vm = new Vue({
el: '#app',
router,
store,
i18n, // 国际化
components: {
App
},
template: '<App/>'
})
3、配置语言包
创建locales文件夹,文件夹中创建zh.js和en.js
zh.js
export const lang = {
Home: {
'title': '首页',
'submit': '提交'
},
Mall: {
'shoppingCart': '购物车',
'detail': '详情'
}
}
en.js
export const lang = {
Home: {
'title': 'Home',
'submit': 'Submit'
},
Mall: {
'shoppingCart': 'ShoppingCart',
'detail': 'Detail'
}
}
4、组件中使用
<template>
<div class="hello">
<div>{{$t('lang.Home.submit')}}</div>
<div @click="switchLangCh">切换中文</div>
<div @click="switchLangEn">切换英文</div>
</div>
</template>
<script>
export default {
name: 'I18nTest',
components: {
},
data () {
return {
value: 'Welcome to Your Vue.js App'
}
},
created () {
},
methods: {
switchLangCh () {
this.$i18n.locale = 'zh-CN' // 切换成中文
},
switchLangEn () {
this.$i18n.locale = 'en-US' // 切换成英文
}
}
}
</script>
<style lang="less" scoped>
</style>
5、App.vue监听语言环境并切换国际化
<template>
<div id="app">
<!-- <keep-alive> -->
<router-view />
<!-- </keep-alive> -->
</div>
</template>
<script>
export default {
name: 'App',
created () {
this.switchI18n()
},
methods: {
switchI18n () {
// 判断当前环境是中文还是英文
const nowLang = navigator.language || navigator.browserLanguage
if (nowLang.indexOf('zh') > -1) {
this.$i18n.locale = 'zh-CN' // 切换国际化成中文
} else {
this.$i18n.locale = 'en-US' // 切换国际化成英文
}
},
}
}
</script>
<style>
</style>