1、安装vue-i18n插件
npm install vue-i18n --save-dev
2、创建中文文件(cn.js)和英文文件(en.js)(创建目录src/static/i18n)
//cn.js
module.exports = {
language: {
name: '中文'
},
user: {
LogOut: '退出登录',
Rights: '权限管理',
systemLog: '系统日志',
}
}
//en.js
module.exports = {
language: {
name: 'English'
},
user: {
LogOut: 'Log out',
Rights: 'Rights management',
systemLog: 'The system log',
}
}
3、在main.js中引入
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) // 通过插件的形式挂载
const i18n = new VueI18n({
locale: localStorage.getItem('langSet') || 'cn', //缓存获取用户中英文选择,没有则默认中文
formatFallbackMessages: true,
messages: {
'cn': require('../static/i18n/cn'), // 中文语言包
'en': require('../static/i18n/en') // 英文语言包
}}
)
new Vue({
router,
i18n,
render: h => h(App)
}).$mount('#app')
4、页面中使用
<el-button @click="switchLanguage" type="danger">{{$t('language.name')}}</el-button>
methods:{
switchLanguage(){
//设置中英文模式
this.$i18n.locale=='cn'?this.$i18n.locale='en':this.$i18n.locale='cn'
//将用户设置存储到localStorage以便用户下次打开时使用此设置
localStorage.setItem('langSet',this.$i18n.locale)
},
}