【vue】中英文切换(使用 vue-i18n )
【vue】中英文切换(使用 vue-i18n )
一、准备工作
1、vue-i18n
1.仓库地址
2.兼容性:支持 Vue.js 2.x 以上版本
1-1.安装依赖vue-i18n
(c)npm install vue-i18n
1-2.使用
在 main.js 中引入 vue-i18n
import Vue from "vue";import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
2、准备本地翻译信息
2-1、element ui的国际化
import enLocale from 'element-ui/lib/locale/lang/en'import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
2-2、zh.js(将我们项目中的语言包与Element的语言包进行合并)
// 注意:一定是 exports,不是 export,否则会报错,报错信息是下列的中的内容不是 stringimport zhLocale from 'element-ui/lib/locale/lang/zh-CN'
export default {
message: {
title: '运动品牌'
},
placeholder: {
enter: '请输入您喜欢的品牌'
},
brands: {
nike: '耐克',
adi: '阿迪达斯',
nb: '新百伦',
ln: '李宁'
},
...zhLocale
}
2-3、en.js(将我们项目中的语言包与Element的语言包进行合并)
import enLocale from 'element-ui/lib/locale/lang/en'export default{
message: {
title: 'Sport Brands'
},
placeholder: {
enter: 'Please type in your favorite brand'
},
brands: {
nike: 'Nike',
adi: 'Adidas',
nb: 'New Banlance',
ln: 'LI Ning'
}
...enLocale
}
2-4、创建带有选项的VueI18n 实例
const i18n = new VueI18n({locale: 'en', // set locale
messages: {
zh: i18n_zh,
en: i18n_en,
}, // set locale messages
})
2-5、把 i18n 挂载到 vue 根实例上
const app = new Vue({router,
i18n,
...App
}).$mount('#app')
二、总结版
import Vue from 'vue'import App from "./App.vue";
import VueI18n from 'vue-i18n'
import ElementLocale from 'element-ui/lib/locale'
import i18n_zh from "./i18n/zh";
import i18n_en from "./i18n/len";
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en', // set locale
messages: {
zh: i18n_zh,
en: i18n_en,
}, // set locale messages
})
ElementLocale.i18n((key, value) => i18n.t(key, value))
const app = new Vue({
router,
i18n,
...App
}).$mount('#app')
三、实战
1、在html中使用
<div id="app"><div style="margin: 20px;">
<h1>{{$t("message.title")}}</h1>
<input style="width: 300px;" class="form-control" :placeholder="$t('placeholder.enter')">
<ul>
<li v-for="brand in brands">{{brand}}</li>
</ul>
</div>
</div>
2、在js 中使用
data () {return {
brands: [this.$t('brands.nike'), this.$t('brands.adi'), this.$t('brands.nb'), this.$t('brands.ln')]
}
},
四、中英文切换
// js方法changeLocale () {
this.$confirm(this.$t('layer.toggle'), this.$t('layer.tips'), {
confirmButtonText: this.$t('button.ok'),
cancelButtonText: this.$t('button.cancel'),
type: 'warning'
}).then(() => {
let locale = this.$i18n.locale
locale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'
}).catch(() => {
this.$message({
type: 'info',
})
})
},
相关资料
- element Ui 国际化
- 使用 vue-i18n 切换中英文
以上是 【vue】中英文切换(使用 vue-i18n ) 的全部内容, 来源链接: utcz.com/z/381012.html