摘要:在vue的电商系统中我们需要支持多种语言切换,满足国际化需求。 vue-i18n是一个vue插件,主要作用就是让项目支持国际化多语言,使用方便快捷,能很轻松的将我们的项目国际化。主要介绍使用vue-i18n实现切换中英文效果。
一、 先安装vue-i18n
使用npm安装vue-i18n
npm install vue vue-i18n --save
二、 引入vue-i18n
在main.js里引入vue-i18n和相关用到的文件
import Vue from 'vue'
import 'babel-polyfill'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import UIComponents from 'ui-components'
import EnComponents from '@/components'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import '@/styles/index.scss' // global css
import App from './App'
import router from './router'
import store from './store'
import i18n from './lang' // Internationalization
import './icons' // icon
import './permission' // permission control
// 全局注册echarts、jsonp
import echarts from 'echarts'
import axios from 'axios'
// register global utility filters.
import * as filters from './filters' // global filter
// register global utility mixins.
import mixin from './utils/mixin'
import * as API_Common from './api/common'
import Cookies from 'js-cookie'
Vue.use(Element, {
size: 'small',
i18n: (key, value) => i18n.t(key, value)
})
Vue.use(UIComponents)
Vue.use(EnComponents)
Vue.use(VueAwesomeSwiper)
Vue.prototype.$echarts = echarts
Vue.prototype.$http = axios
Vue.prototype.$message.success = function(text) {
Vue.prototype.$message({
showClose: true,
message: text,
type: 'success',
duration: 5000
})
}
Vue.prototype.$message.error = function(text) {
Vue.prototype.$message({
showClose: true,
message: text,
type: 'error',
duration: 5000
})
}
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
Vue.mixin(mixin)
Vue.config.productionTip = false
API_Common.getLanguage(Cookies.get('adminLanguage') || 'zh').then(response => {
new Vue({
el: '#app',
beforeCreate() { this.$i18n.setLocaleMessage(Cookies.get('adminLanguage') || 'zh', response) },
router,
store,
i18n,
template: '<App/>',
components: { App }
})
}).catch(() => {
Element.Message.error('设置语言失败,请刷新页面重试!')
new Vue({
el: '#app',
router,
store,
i18n,
template: '<App/>',
components: { App }
})
})
三、 从后台获取语言包数据
1.新建文件夹lang并在里index.js里引入vue-i18n并且创建带有选项的 VueI18n 实例
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
Vue.use(VueI18n)
const messages = {
}
const i18n = new VueI18n({
locale: Cookies.get('adminLanguage') || 'zh', // set locale
messages // set locale messages
})
export default i18n
注意:文中有js-cookie 实例中加载了从后台请求过来的语言包
2.在vuex store里modules新建APP.js里切换的时候,根据语言加载各个国家的语言
import Cookies from 'js-cookie'
const app = {
state: {
sidebar: {
opened: !+Cookies.get('adminSidebarStatus'),
withoutAnimation: false
},
device: 'desktop',
language: Cookies.get('adminLanguage') || 'zh'
},
mutations: {
TOGGLE_SIDEBAR: state => {
if (state.sidebar.opened) {
Cookies.set('adminSidebarStatus', 1)
} else {
Cookies.set('adminSidebarStatus', 0)
}
state.sidebar.opened = !state.sidebar.opened
state.sidebar.withoutAnimation = false
},
CLOSE_SIDEBAR: (state, withoutAnimation) => {
Cookies.set('adminSidebarStatus', 1)
state.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation
},
TOGGLE_DEVICE: (state, device) => {
state.device = device
},
SET_LANGUAGE: (state, language) => {
state.language = language
Cookies.set('adminLanguage', language)
}
},
actions: {
toggleSideBar({ commit }) {
commit('TOGGLE_SIDEBAR')
},
closeSideBar({ commit }, { withoutAnimation }) {
commit('CLOSE_SIDEBAR', withoutAnimation)
},
toggleDevice({ commit }, device) {
commit('TOGGLE_DEVICE', device)
},
setLanguage({ commit }, language) {
commit('SET_LANGUAGE', language)
}
}
}
export default app
3.在utils里新建文件转换router.meta.title,用于面包屑侧边栏标签视图
export function generateTitle(title) {
return this.$t('route.' + title) // $t :this method from vue-i18n ,inject in @/lang/index.js
}
4.在utils里新建文件request.js 在request方法里加 如果是刷新token或者登录,不需要检查token直接请求语言包
export default function request(options) {
console.log(11, options)
// 如果是刷新token或者登录,不需要检查token直接请求。
if (options.url.indexOf('systems/admin-users/login') + options.url.indexOf('systems/admin-users/token') + options.url.indexOf('validator') + options.url.indexOf('language') > -4) {
// console.log(options.url + ' | 请求的刷新token或是登录,不需要检查token直接请求。')
return service(options)
}
return new Promise((resolve, reject) => {
checkToken(options).then(() => {
service(options).then(resolve).catch(reject)
})
})
}
四、根据vuex切换语言动态加载语言包
<script>
import * as API_Common from '../../api/common'
export default {
computed: {
language() {
return this.$store.getters.language
}
},
methods: {
handleSetLanguage(lang) {
API_Common.getLanguage(lang).then(async response => {
this.$i18n.setLocaleMessage(lang, response)
await this.$nextTick()
this.$i18n.locale = lang //通过切换locale的值来实现语言切换
this.$store.dispatch('setLanguage', lang)
this.$message({
message: lang === 'zh' ? '语言切换成功' : 'switch language success',
type: 'success'
})
})
}
}
}
</script>
五、页面使用
{{$t('group.text1')}}
vue 组件form表单使用 :label="$t('group.text1')"