使用vue-i18n實現多語言
阿新 • • 發佈:2019-01-01
1. 前言
(1) 需求
Vue工程,需要實現多語言切換功能。
(2) vue-i18n外掛
npm中對vue-i18n的描述及文件
我們將使用這個外掛實現多語言。
(3) 相容性
支援Vue.js 2.x以上版本
2. 實戰
(1) 安裝
npm install vue-i18n
(2) 工程中使用
[1] 在main.js中引入vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
[2] 語言資源
const messages = {
//英文
en: {
message: {
hello: 'hello' ,
about: 'about',
welcome: "Welcome"
}
},
//簡體中文
zhCHS: {
message: {
hello: '你好',
about: '關於',
welcome: "歡迎"
}
},
//繁體中文
zhCHT: {
message: {
hello: '妳好',
about: '關於',
welcome: "歡迎"
}
}
[3] VueI18n例項
const i18n = new VueI18n({
//定義預設語言
locale: 'en',
messages
})
[4] 掛載到Vue的例項上
new Vue({
el: '#app',
router,
i18n, //<====
template: '<App/>',
components: { App }
})
[5] 標記在HTML中
注意:這裡是$t
h3 {{ $t("message.hello") }}
完成上述功能後,我們執行,可以看到內容顯示為hello
,修改上述第三步的locale
為zhCHS
後執行,可以看到頁面變為了你好
。
[6] 標記在js中
computed:{
welcomeMessage(){
return this.username + ', '+ this.$t("message.welcome");
}
},
(3) 功能進階
[1] 動態切換語言
實際專案中,往往需要動態切換語言,比如當用戶點選了其需要的語言。
vue-i18n 提供了一個全域性配置引數叫 “locale”,通過改變 locale 的值可以實現不同語言的切換。
在頁面中只需要在切換時,修改this.$i18n.locale
的值即可。
this.$i18n.locale='zhCHS'
[2] 語言包
實際開發中,語言資源會很多,通常會單獨作為語言包的檔案放置在工程中。
1) 資原始檔
在根目錄下的static資料夾中新建lang資料夾,作為語言包。
將不同語言儲存成json物件,完成3個js如下。
//en.js
module.exports={
message: {
hello: 'hello',
about: 'about',
welcome: "Welcome"
}
}
//zhCHS.js
module.exports={
message: {
hello: '你好',
about: '關於',
welcome: "歡迎"
}
}
//zhCHT.js
module.exports={
message: {
hello: '妳好',
about: '關於',
welcome: "歡迎"
}
}
2) main.js中引入
import LangEn from '../static/lang/en'
import LangZhCHS from '../static/lang/zhCHS'
import LangZhCHT from '../static/lang/zhCHT'
const i18n = new VueI18n({
locale: 'en',
messages:{
'en': LangEn,
'zhCHS': LangZhCHS,
'zhCHT': LangZhCHT
}
})
3) 資源中換行
在開發過程中遇到key對應的內容中,需要進行換行的。用<br>
或者<br />
都會直接將字元輸出到頁面。
解決方式:將內容寫入繫結元素的v-html
中。
例如:
"wish_you_good_luck": "Wishing You a Year of Prosperity. <br /> Good Fortune Starts Here!"
p(v-html='$t("message.wish_you_good_luck")')