1,支持vue2以上版本
2,安装:npm install vue-i18n
3,目录:
4,创建i18n.js文件
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from 'element-ui/lib/locale';
import zh from './langs/zh'
import en from './langs/en'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const messages = {
en: Object.assign(en, enLocale),
zh: Object.assign(zh, zhLocale)
}
console.log(messages.zh)
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh',
messages
})
locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换
export default i18n
5,创建zh.js文件
// 注意:一定是 exports,不是 export,否则会报错,报错信息是下列的中的内容不是 string
module.exports = {
message: {
title: '运动品牌'
},
placeholder: {
enter: '请输入您喜欢的品牌'
},
brands: {
nike: '耐克',
adi: '阿迪达斯',
nb: '新百伦',
ln: '李宁'
}
}
6.创建en.js文件
module.exports = {
message: {
title: 'Sport Brands'
},
placeholder: {
enter: 'Please type in your favorite brand'
},
brands: {
nike: 'Nike',
adi: 'Adidas',
nb: 'New Banlance',
ln: 'LI Ning'
}
}
7.在main.js中引入
import i18n from './i18n/i18n'
window.app = new Vue({
el: '#app',
router,
store,
i18n,
components: { App },
template: '<App/>'
})
8.本人遇到的问题
(1)在template中可以直接这样用{{$t(“brands.nike”)}},没有问题,切换语言的时候,能够正常切换;
但是在js里面,这样用在切换语言时这一数据不变动
data() {
return {
kk: this.$t("brands.nike"),
}
}
(2)原因:data 初始化的时候拿到这些被国际化的值,并不能响应变化,需要把变量放在computed 属性里
(3)解决:
computed: {
kk: function () {
return this.$t("brands.nike");
},
arr: function () {
let aa=[
a1: this.$t("brands.nike"),
a2: this.$t("brands.nike"),
a3: this.$t("brands.nike"),
]
return aa;
},
}
这样就可以正常切换了.