npm安裝vue-i18n
npm install vue-i18n -S
查看package.json
準(zhǔn)備目錄結(jié)構(gòu)和配置文件
i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const DEFAULT_LANG = 'en'
const LOCALE_KEY = 'localeLanguage'
const locales = {
zh: require('./zh.js'),
en: require('./en.js'),
}
const i18n = new VueI18n({
locale: DEFAULT_LANG,
messages: locales,
})
export const setup = lang => {
if (lang === undefined) {
lang = window.localStorage.getItem(LOCALE_KEY)
if (locales[lang] === undefined) {
lang = DEFAULT_LANG
}
}
window.localStorage.setItem(LOCALE_KEY, lang)
Object.keys(locales).forEach(lang => {
document.body.classList.remove(`lang-${lang}`)
})
document.body.classList.add(`lang-${lang}`)
document.body.setAttribute('lang', lang)
Vue.config.lang = lang
i18n.locale = lang
}
// setup()
export default i18n
在i18n.js文件中擅威,我們不需要關(guān)注其他的配置,只需看懂這2項(xiàng)配置即可景描。
zh.js
module.exports = {
userInfo:{
name:'姓名',
number:'聯(lián)系方式',
EMail:'電子郵箱',
massage:'留言內(nèi)容',
followUs:'聯(lián)系我們'
}
}
en.js
module.exports = {
userInfo:{
name:'Name',
number:'Contact information',
EMail:'E-mail',
massage:'Message content',
followUs:'Follow us'
}
}
main.js引入使用
import i18n from './i18n/i18n'
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount('#app')
使用方式
在.vue文件中使用
語法是{{$t('標(biāo)識(shí)')}}
<div>{{$t('userInfo.name')}}
頁面顯示中文還是英文取決于i18n.js文件當(dāng)中的這一行命令
const DEFAULT_LANG = 'zh'
當(dāng)DEFAULT_LANG = 'zh',頁面顯示中文
當(dāng)DEFAULT_LANG = 'en', 頁面顯示英文
案例:實(shí)現(xiàn)中英切換
<template>
<div>
{{$t('userInfo.name')}}:<el-input placeholder=""></el-input>
<el-button type="primary" @click="changeLang">中/英</el-button>
</div>
</template>
<script>
export default {
methods:{
changeLang(){
const lang = this.$i18n.locale //獲取當(dāng)前頁面默認(rèn)使用的語言
console.log(lang) //控制臺(tái)輸出 'zh'
// 實(shí)現(xiàn)中英切換
if(lang == 'zh'){ //如果默認(rèn)是中文芒粹,在用戶點(diǎn)擊時(shí)就切換到英文狀態(tài)
this.$i18n.locale = 'en'
}else {
this.$i18n.locale = 'zh'
}
}
}
}
</script>
<style>
</style>