npm i -S element-ui vue-i18n js-cookie
複製代碼
zh.js
export default {
common: {
confirm: '肯定',
cancel: '取消',
home: '首頁'
},
login: {
login: '登陸',
logout: '退出'
},
header: {
message: '這是公共的頭部組件'
},
footer: {
message: '這是公共的底部組件'
}
}
en.js
export default {
common: {
confirm: 'confirm',
cancel: 'cancel',
home: 'home'
},
header: {
message: 'this is a common header component'
},
footer: {
message: 'this is a common footer component'
},
login: {
login: 'login',
logout: 'logout'
}
}
複製代碼
import VueI18n from 'vue-i18n'
import enLocale from './en'
import zhLocale from './zh'
const messages = {
en: {
...enLocale
},
zh: {
...zhLocale
}
}
const i18n = new VueI18n({
locale: 'zh',
messages
})
export default i18n
複製代碼
import Vue from 'vue'
import i18n from './lang'
Vue.use(i18n)
new Vue({
el: '#app',
router,
store,
i18n, // 便於能夠直接在組件中經過this.$i18n使用,也能夠按需引用
render: h => h(App)
})
複製代碼
<template>
<div class="common_header">
<el-row>
<el-col :span="12">
{{$t('header.message')}}
</el-col>
<el-col :span="12">
<el-button type="primary" @click="login">{{$t('login.login')}}</el-button>
</el-col>
</el-row>
</div>
</template>
複製代碼
因爲咱們VueI18n中定義的是中文,這是頁面顯示的'這是公共的頭部組件',login: '登陸',修該VueI18n實例屬性locale的值爲en,刷新頁面,頁面顯示 'this is a common header component','login',說明多語言配置成功。vue
<el-select v-model="language" placeholder="請選擇語言" @change="changeLanguage">
<el-option
v-for="item in languageOptions"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
複製代碼
changeLanguage (language) {
this.$i18n.locale = language
}
複製代碼
切換語言時,頁面將自動完成語言類型的切換。
const i18n = new VueI18n({
locale: Cookies.get('language') || 'zh',
messages
})
切換語言時候保存到Cookies
Cookies.set('language', language)
複製代碼
這是再去刷新頁面,將會採用最後咱們保存在cookie中的語言。vuex
changeLanguage (v) {
this.$store.dispatch('switchLanguage', v)
this.$i18n.locale = v
}
在state中:
language: Cookies.get('language') || 'zh'
複製代碼
languageOptions () {
let languageOptions
if (this.$store.state.language === 'zh') {
languageOptions = [
{
value: 'zh',
label: '中文'
},
{
value: 'en',
label: '英文'
}
]
} else {
languageOptions = [
{
value: 'zh',
label: 'Chinese'
},
{
value: 'en',
label: 'English'
}
]
}
return languageOptions
}
複製代碼
效果以下: npm
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'
複製代碼
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
}
複製代碼
Vue.use(i18n)
修改成
Vue.use(ElementUI, {
i18n: (key, value) => i18n.t(key, value)
})
複製代碼