main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import VueI18n from 'vue-i18n'
import ElementUI from 'element-ui';
Vue.use(ElementUI);
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
//this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {
'en-US': require('./assets/languages/en'), // 英文语言包
'zh-CN': require('./assets/languages/zh-CN'), // 中文语言包
}
})
console.log(i18n.locale)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
i18n,
components: { App },
template: '<App/>'
})
App.vue文件
<template>
<div id="app" class="hello">
<app-footer></app-footer>
<!-- <router-view></router-view> -->
</div>
</template>
<script>
import appFooter from "@/components/app-footer"
export default {
name: 'App',
data() {
return {
}
},
components: {
appFooter
},
methods: {
},
mounted() {
}
}
</script>
<style scoped>
</style>
组件文件
<template>
<div>
<div @click="changeLangEvent">
点我
</div>
<div>
<span>{{$t('m.music')}}</span>
</div>
</div>
</template>
<script>
export default {
name: "app",
data() {
return {
lang: "zh-CN"
}
},
methods: {
/**
* 切换语言
*/
changeLangEvent() {
this.$confirm('确定切换语言吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
console.log(this.lang)
if (this.lang === 'zh-CN') {
this.lang = 'en-US';
this.$i18n.locale = this.lang;//关键语句
} else {
this.lang = 'zh-CN';
this.$i18n.locale = this.lang;//关键语句
}
}).catch(() => {
this.$message({
type: 'info',
});
});
}
}
}
</script>
语言包
export const m = {
music: '网易云音乐',
findMusic: '发现音乐',
myMusic: '我的音乐',
friend: '朋友',
musician: '音乐人',
download: '下载客户端'
}
export const m = {
music: 'Music',//网易云音乐
findMusic: 'FIND MUSIC',//发现音乐
myMusic: 'MY MUSIC',//我的音乐
friend: 'FRIEND',//朋友
musician: 'MUSICIAN',//音乐人
download: 'DOWNLOAD'//下载客户端
}