1. vue-i18n implementation language switching vue-i18n be installed, using the language selected by the user's cookie, cookie to install
npm install vue-i18n
npm install js-cookie
2. Create lang file, then the new folder lang.js, package setlang () and getLang () method, the user selects a language used to access the cookie
export default {
setLang (lang) {
window.localStorage.setItem('user_lang', lang)
},
getLang (defaultLang) {
let localLang = window.localStorage.getItem('user_lang')
if (localLang === null) {
return defaultLang
} else {
return localLang
}
}
}
3. Add New zh.js and en.js language pack lang file
module.exports = {
layout: {
home: '首页',
scan: '扫一扫',
person: '个人'
}
}
module.exports = {
layout: {
home: 'home',
scan: 'scan',
person: 'person'
}
}
4. vue-i18n incorporated in and lang.js main.js
import VueI18n from 'vue-i18n'
import LangStorage from './lang/lang'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: LangStorage.getLang('zh'),//调用lang.js的getLang()方法获取语言
// locale: 'zh',
messages: {
'zh': require('./lang/zh'),//引入语言包
'en': require('./lang/en'),//引入语言包
}
})
new Vue({
el: '#app',
i18n,//使用i18n
components: { App },
template: '<App/>'
})
5. Use the page
<mt-header :title="$t('layout.home')" >
<span>{{$t('layout.home')}}</span>
<select slot="left" v-model='lang' class="lang">//语言切换
<option value="zh">中文</option>
<option value="en" >English</option>
</select>
</mt-header>
<!--在js使用-->
<script>
alert(this.$t('layout.home'))
</script>
6.wacth monitor language switching method
watch: {
lang (val, olfval) {
this.$i18n.locale = val//切换语言
LangStorage.setLang(this.$i18n.locale)//把语言存到cookie
}
},
7. Reference: https://www.jianshu.com/p/b022535713c3 , https://www.cnblogs.com/listen9436/p/10525532.html