vue-i18n官方文檔:http://kazupon.github.io/vue-i18n/en/started.html
element-ui文檔: http://element-cn.eleme.io/#/zh-CN/component/i18n
資料分享完了,現(xiàn)在開始總結vue-i18n使用方法:
-
1、先看一下我的項目結構
7MD}500FK{BG~NV2IC3J0@3.png - 2、廢話不多說,直接上代碼:
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中拿到用戶的語言選擇,如果沒有,那默認中文。
const i18n = new VueI18n({
locale: localStorage.lang || 'cn',
messages,
})
locale.i18n((key, value) => i18n.t(key, value)) //為了實現(xiàn)element插件的多語言切換
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;
然后寫一個模板測試一下:
<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>
可能遇到的問題
1、記不住切換后的語言
我們在切換語言后,刷新一下瀏覽器又成了默認語言。那么可以在切換語言的方法中加入 localStorage.setItem("language", "你定義的語言包,如zh/en")
2、將this.$t() 寫到了data屬性里,切換語言不起作用
data是一次性生產(chǎn)的,你這么寫只能是在 data 初始化的時候拿到這些被國際化的值,并不能響應變化。
官方的解決辦法是,建議我們將表達式寫到 computed 屬性里,不要寫到 data 里
3、后臺獲取過來的動態(tài)數(shù)據(jù),在切換國際語言后不起作用
在witch中監(jiān)聽 i18n語言變化,重新調(diào)取接口。
watch: {
'$i18n.locale'() {
// 這里寫調(diào)用接口的邏輯
}
}
好了,到這里就結束了,有時間還是多去看看vue-i18n文檔
最后聲明一下,這篇文章是借鑒下面這位老兄的文章寫的:https://segmentfault.com/a/1190000012779120#articleHeader1
