vue-i18n官方文檔:http://kazupon.github.io/vue-i18n/en/started.html
element-ui文檔: http://element-cn.eleme.io/#/zh-CN/component/i18n
資料分享完了创肥,現(xiàn)在開(kāi)始總結(jié)vue-i18n使用方法:
-
1蒸其、先看一下我的項(xiàng)目結(jié)構(gòu)
7MD}500FK{BG~NV2IC3J0@3.png - 2锚贱、廢話不多說(shuō),直接上代碼:
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import i18n from './i18n/i18n';
Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
i18n,
components: { App },
template: '<App/>'
})
i18n.js
import Vue from 'vue'
import locale from 'element-ui/lib/locale';
import VueI18n from 'vue-i18n'
import messages from './langs'
Vue.use(VueI18n)
//從localStorage中拿到用戶的語(yǔ)言選擇纵朋,如果沒(méi)有乔宿,那默認(rèn)中文膳汪。
const i18n = new VueI18n({
locale: localStorage.lang || 'cn',
messages,
})
locale.i18n((key, value) => i18n.t(key, value)) //為了實(shí)現(xiàn)element插件的多語(yǔ)言切換
export default i18n
cn.js
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
const cn = {
message: {
'hello': '你好唯蝶,世界',
'msg': '提示',
}
}
export default cn;
en.js
import enLocale from 'element-ui/lib/locale/lang/en'
const en = {
message: {
'hello': 'hello, world',
'msg': 'point out',
}
}
export default en;
然后寫(xiě)一個(gè)模板測(cè)試一下:
<template>
<div class="hello">
<el-button type="primary" @click="switchChinese()">切換中文</el-button>
<el-button type="primary" @click="switchEnlish()">切換英文</el-button>
<p>{{$t('message.hello')}}</p>
<p>{{$t('message.msg')}}</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
switchChinese(){
this.$i18n.locale = 'cn';
},
switchEnlish(){
this.$i18n.locale = 'en';
}
}
}
</script>
可能遇到的問(wèn)題
1、記不住切換后的語(yǔ)言
我們?cè)谇袚Q語(yǔ)言后遗嗽,刷新一下瀏覽器又成了默認(rèn)語(yǔ)言粘我。那么可以在切換語(yǔ)言的方法中加入 localStorage.setItem("language", "你定義的語(yǔ)言包,如zh/en")
2痹换、將this.$t() 寫(xiě)到了data屬性里征字,切換語(yǔ)言不起作用
data是一次性生產(chǎn)的,你這么寫(xiě)只能是在 data 初始化的時(shí)候拿到這些被國(guó)際化的值娇豫,并不能響應(yīng)變化匙姜。
官方的解決辦法是,建議我們將表達(dá)式寫(xiě)到 computed 屬性里冯痢,不要寫(xiě)到 data 里
3氮昧、后臺(tái)獲取過(guò)來(lái)的動(dòng)態(tài)數(shù)據(jù)框杜,在切換國(guó)際語(yǔ)言后不起作用
在witch中監(jiān)聽(tīng) i18n語(yǔ)言變化,重新調(diào)取接口袖肥。
watch: {
'$i18n.locale'() {
// 這里寫(xiě)調(diào)用接口的邏輯
}
}
好了咪辱,到這里就結(jié)束了,有時(shí)間還是多去看看vue-i18n文檔
最后聲明一下昭伸,這篇文章是借鑒下面這位老兄的文章寫(xiě)的:https://segmentfault.com/a/1190000012779120#articleHeader1