i18n在vue項目里的使用
1.引入
npm install vue-i18n -S
2.文件結構如下
├─application 應用目錄 │ ├─src 開發目錄 │ │ ├─i18n 語言包目錄 │ │ │ ├─en_us.json 英文 │ │ │ ├─zh_cn.json 中文 │ │ │ │ │ ├─util 模塊 │ │ │ ├─i18n.js 語言包配置文件
3.為了使項目結構更清晰,我們單獨在tools文件夾中新建i18n.js文件,文件內容如下
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 以下為語言包單獨設置的場景,單獨設置時語言包需單獨引入
const messages = {
'zh_cn': require('../i18n/zh_cn'), // 中文語言包
'en_us': require('../i18n/en_us') // 英文語言包
}
// 最后 export default,這一步肯定要寫的。
export default new VueI18n({
// set locale 默認顯示中文
locale : (function() {
if (localStorage.getItem('lang')) {
return localStorage.getItem('lang')
} else {
return 'zh_cn'
}
})(),
messages : messages // set locale messages
})
4.然后在main.js里面全局引入並掛載
//...其他代碼
//引入多語言支持
import i18n from './util/i18n'
//...其他代碼
new Vue({
i18n, //掛載i18n
router,
store,
render: (h) => h(App)
}).$mount('#root')
5.在i18n目錄里面的zh.js和cn.js如下
zh_cn.json
{
login:{
'title' : '軟件系統',
'username' : '請輸入用戶名',
'password' : '請輸入密碼',
'login' : '登錄',
'language' : '請選擇語言'
},
}
en_us.json
{
login:{
'title' : 'Software system',
'username' : 'Please enter the user name',
'password' : 'Please enter your password',
'login' : 'Login',
'language' : 'Please select language'
},
}
6.這樣我再組件login.vue里面就可以使用了
//template
<h3>{{$t("login.title")}}</h3>
<button @click='langToggle'>en/中</button>
//js
methods:{
langToggle(command) {
if (this.$i18n.locale === 'zh_cn') {
this.$i18n.locale = 'zh_cn'
} else if (this.$i18n.locale === 'en_us') {
this.$i18n.locale = 'en_us'
}
localStorage.setItem('lang', command)
this.$i18n.locale = command
}
}
