1、安装
npm install i18n
2、在main.js中引入
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 多语言实例
const i18n = new VueI18n({
locale: (function () {
if (localStorage.getItem('lang')) {
return localStorage.getItem('lang')
}
return 'zh'
}()),
messages: {
'zh': require('./assets/i18n/zh'), // 中文语言包
'en': require('./assets/i18n/en') // 英文语言包
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
i18n,
router,
store,
components: { App },
template: '<App/>'
})
引入这些都没什么好说的,主要是多语言实例,因为切换语言的关系 ,我将语言标识保存在了 localStorage 中,这里记得一点就是一定要有默认语言,不然新设备访问的时候localStorage中没有值就会出现BUG。
3、建立语言包
语言包只要放在src下即可,这里我只用到了中文和英语。然后语言包在main.js中引入,上面main.js中我已经写了
messages: {
'zh': require('./assets/i18n/zh'), // 中文语言包
'en': require('./assets/i18n/en') // 英文语言包
}
然后我们在看一下语言包的里面怎么写
其实只需要将对应的键值对写好在 module.exports 导出即可使用
4、使用
1、在标签中使用
<div class="register_heds">{{$t("login.title")}}</div>
2、在input 的 placeholder 中使用,其实就是vue的 v-bind
<input type="password" :placeholder="$t('login.password')" maxlength="24" v-model="log_password">
3、在JS中使用
this.$t('login.clause')
4、语言切换方法
Language(){
if(this.$i18n.locale === 'zh'){
this.$i18n.locale = 'en'
localStorage.setItem('lang','en')
}else{
this.$i18n.locale = 'zh'
localStorage.setItem('lang','zh')
}
}