在基于vue-cli項目開發過程中,多語言切換功能可使用vue-i18插件,具體實現方法如下:
step1: 在項目中安裝vue-i18插件
cnpm install vue-i18n --save-dev
step2:在項目的入口文件main.js中引入vue-i18n插件
import Vue from 'vue' import router from './router' import VueI18n from 'vue-i18n' Vue.use(VueI18n) const i18n = new VueI18n({ locale: 'zh', // 語言標識 messages: { 'zh': require('./assets/lang/zh'), 'en': require('./assets/lang/en') } }) // vue實例中引入 /* eslint-disable no-new */ new Vue({ el: '#app', i18n, router, template: '<Layout/>', components: { Layout }, }) step3:頁面中使用
在模板中使用時,大概有以下3種情況,若有疏漏,望大家指正
zh.js
module.exports = { menu : { home:"首頁" }, content:{ main:"這里是內容" } } en.js
module.exports = { menu : { home:"home" }, content:{ main:"this is content" } } 1)在標簽內作為正文內容
<div class="title">{{$t('menu.home')}}</div> 2)作為標簽屬性使用
<input :placeholder="$t('content.main')" type="text"> 3)作為js中文字使用時
console.log(this.$t('content.main')); 4)待補充...
step4:頁面上進行中英文切換,在中英文切換的按鈕上綁定事件,如下:
tabEn: function () { this.$i18n.locale = 'en' }, tabCn: function () { this.$i18n.locale = 'zh' } 至此,vue-i18n插件使用完結。
總結
以上所述是小編給大家介紹的Vue中使用vue-i18插件實現多語言切換功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
|
新聞熱點
疑難解答