In the vue project, $t('') directly calls this function in html { { $t('login.title') }}
$t is a method attached to Vue.prototype after the introduction of internationalization, accepting a string as a parameter
<div class="title-container">
<h3 class="title">
{
{ $t('login.title') }}
</h3>
</div>
//---------$t('login.title') 我理解的意思是去当前语言环境下login对象的title值
1.Introduce vue-i18n into main.js
// 国际化 这个文件是本地创建的 主要是获取当前语言环境和相应的变量值
import i18n from './lang'
new Vue({
el: '#app',
i18n,
render: h => h(App)
})
2. The language environment of the browser is different, and different language configuration files are set accordingly.
// ./lang/index.js
import Vue from 'vue' //引入vue
import VueI18n from 'vue-i18n' //引入vue的国际化插件
import Cookies from 'js-cookie' //我这里需要,所以引入轻量级的处理cookies的js
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import zhLocale from './zh' //本地创建的中文环境配置文件
import enLocale from './en' //本地创建的英文环境配置文件
Vue.use(VueI18n) // 通过插件的形式挂载,通过全局方法 Vue.use() 使用插件
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
}
//获取当前语言环境,通过后台返回的语言或者浏览器语言环境
export function getLanguage() {
const chooseLanguage = Cookies.get('language')//取后台设置的语言
if (chooseLanguage) return chooseLanguage
//如果后台没有返回语言则根据浏览器的语言环境返回语言变量
const language = (navigator.language || navigator.browserLanguage).toLowerCase()
const locales = Object.keys(messages)//获取前端设置的所有语言
//遍历所有语言值组成的数组,匹配前端设置的语言能匹配到就返回改语言值
for (const locale of locales) {
if (language.indexOf(locale) > -1) {
return locale
}
}
//如果都没匹配到就直接返回英文
return 'en'
}
const i18n = new VueI18n({
//语言标识 this.$i18n.locale 通过切换locale的值来实现语言切换
//如:this.$i18n.locale='en' 直接切换成英文,仅限于配置了语言的一些变量
locale: getLanguage(),//调的上边这个函数
messages //上边配置的语言标识对应的不同配置
})
export default i18n
3. Create files corresponding to different language identifiers, taking the Chinese environment as an example
// ./lang/index.js 创建文件 存储语言对应的一些变量
export default {
login: {
title: '登录表单',
},
warning: '警告信息'
}