1.安装:npm install vue-i18n 2.在main.js引入i18n,注册,并设置element语言
import i18n from './lang'
// set ElementUI lang ,兼容elementui写法
Vue.use(ElementUI, { i18n: (key, value) => i18n.t(key, value) })
new Vue({
el: '#app',
router,
store,
i18n,
render: h => h(App)
})
3.src/lang/index.js文件中
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import enLocale from './en'
import zhLocale from './zh'
Vue.use(VueI18n)
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
},
}
export function getLanguage() {
const chooseLanguage = Cookies.get('language')
// const chooseLanguage = localStorage.get('language')
if (chooseLanguage) return chooseLanguage
// if has not choose language
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({
// set locale
// options: en | zh | es
locale: 'zh',
// set locale messages
messages
})
export default i18n
4.准备语言包
5.使用方式 (1)双括号{{$t('xxx.yyy')}}
<p @click="showWarning">{{$t('login.username')}}
(2)绑定到属性上 :prop="$t('xxx.yyy')"
:placeholder="$t('placeholder.date')">
(3)在js中使用${this.$t('xxx.yyy')}
//注意使用反引号
`${this.$t('xxx.yyy')}`