1.安装插件(官网)
npm install vue-i18n@8 --save
2.配置中英文语言包
2-2.语言包导出形式
3.main.js配置
import Vue from 'vue'
// 引入i18n插件
import VueI18n from 'vue-i18n'
// 引入语言包
import en from '@/local/en'
import zh from '@/local/zh'
// 使用VueI18n插件
Vue.use(VueI18n)
const messages = {
en,
zh
}
// 创建 VueI18n 实例
const i18n = new VueI18n({
locale: "en", // 设置默认语言
messages: {
en,
zh,
},
});
// 保存语言值:1.获取之前保存的语言设置,2.动态切换语言
localStorage.setItem("langType", "en");
// 创建vue实例
new Vue({
router,
store,
i18n,
render: h => h(App),
// beforeCreate(){
// Vue.prototype.$bus = this;
// }
}).$mount('#app')
3.i18n使用
3-1.语言切换
change() {
this.$i18n.locale = this.$i18n.locale == "en" ? "zh" : "en";
localStorage.setItem("langType", this.$i18n.locale);
},
3-2.请求配置
// 请求拦截器
service.interceptors.request.use(function (config) {
// 添加token
if (localStorage.getItem("token")) {
config.headers.token = localStorage.getItem("token")
}
config.headers.Lang = localStorage.getItem("langType");
return config
}, function (error) {
return Promise.reject(error)
})
3-3-1.模版中使用
<template>
<div>
{{$t('home.首页')}}
</div>
</template>
3-3-2. vue中使用【除props,beforeCreate钩子函数不能拿到this外】
<template>
<div>
{{title}}
</div>
</template>
<script>
export default {
name: '',
components:{},
props:{},
data(){
return {
pageName:this.$t('home.首页')
}
},
computed: {},
created() {
},
mounted() {},
methods: {
change(){
this.$t('home.语言')
}
},
}
</script>