Abstract: In Vue's e-commerce system , we need to support multiple language switching to meet internationalization needs. Vue-i18n is a Vue plug-in. The main function is to allow the project to support internationalization and multi-language, which is convenient and fast to use, and can easily internationalize our project. It mainly introduces the use of vue-i18n to achieve the effect of switching between Chinese and English.
1. Install vue-i18n first
Install vue-i18n using npm
npm install vue vue-i18n --save
2. Introducing vue-i18n
Introduce vue-i18n and related files in main.js
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 }
})
})
3. Obtain language pack data from the background
1. Create a new folder lang and introduce vue-i18n in index.js and create a VueI18n instance with options
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
Note: The js-cookie instance in the text loads the language pack requested from the background
2. When switching in the new APP.js of modules in the vuex store, load the language of each country according to the language
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. Create a new file in utils to convert router.meta.title for breadcrumbs sidebar label view
export function generateTitle(title) {
return this.$t('route.' + title) // $t :this method from vue-i18n ,inject in @/lang/index.js
}
4. Create a new file request.js in utils and add it to the request method. If you refresh the token or log in, you don't need to check the token and request the language pack directly
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)
})
})
}
4. Dynamically load language packs according to vuex switch language
<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>
5. Page usage
{{$t('group.text1')}}
vue 组件form表单使用 :label="$t('group.text1')"