【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,否則會報錯,報錯資訊是下列的中的內容不是 string import 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', }) }) },
相關資料