最近在做的一個網(wǎng)站需要加上一個英文版(看過之前文章的會知道),點擊按鈕切換中文/英文,在這里記錄下實現(xiàn)過程。
需求:網(wǎng)站實現(xiàn)中英文切換
項目環(huán)境:vue + vue-cli + element-ui
1、首先 npm 安裝 i18n 國際化插件:npm install vue-i18n --save;
2、在 src 下新建一個目錄 i18n(目錄名隨意),新建i18n.js文件,再建一個子文件目錄 langs,里面包含 cn/en/index.js文件,目錄結(jié)構(gòu)如下:
image.png
3、把安裝好的 i18n 引入 main.js 文件中,并且在 app 根組件中注入;
import i18n from './i18n/i18n'
window.app = new Vue({
el: '#app',
router,
store,
i18n, //注入根目錄下,千萬不能忘記
components: { App },
template: '<App/>'
})
4、這里需要用的存儲store,在src下新建store, index.js文件
import Vue from 'vue'
import Vuex from 'vuex' //引入vuex之前,先npm安裝 npm install vuex --save
Vue.use(Vuex)
export default new Vuex.Store({
state: {
lang: localStorage.lang || 'cn'
},
mutations: {
switchLang (state, lang) {
state.lang = lang
window.app.$i18n.locale = lang
localStorage.setItem('lang', lang)
}
},
actions: {}
})
5、開始在 i18n.js 中編寫代碼;
import Vue from 'vue'
import locale from 'element-ui/lib/locale' // element-ui 國際化
import VueI18n from 'vue-i18n'
import messages from './langs' // 這里是調(diào)用 langs/index.js
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.lang || 'cn', // 語言標識
messages
})
locale.i18n((key, value) => i18n.t(key, value)) // 重點:為了實現(xiàn)element插件的多語言切換
export default i18n
6、langs目錄下的 index.js文件;
import en from './en'
import cn from './cn'
export default {
cn,
en
}
7、langs目錄下的 en.js 文件;
import enLocale from 'element-ui/lib/locale/lang/en' // element-ui 國際化 英文
// 這里把翻譯好的英文以對象的格式包裹起來,建議以模塊來劃分,這樣在調(diào)用起來方便效率,舉例說明:導航菜單欄
const en = {
navbar: { // 取導航的英文來包裹其內(nèi)的子對象
'home': 'Home', //前面的第一個英文home為頁面將調(diào)用的
'Product description': 'Product description',
'Login': 'Login',
'Register': 'Register',
'Simplified Chinese': 'Simplified Chinese'
},
...enLocale
}
export default en // vuex方法,映射到英文上
image.png
image.png
8、langs目錄下的 cn.js 文件;
import zhLocale from 'element-ui/lib/locale/lang/zh-CN' // element-ui 國際化 中文
// 同理en.js文件,只是這里改成中文了
const cn = {
navbar: {
'home': '首頁',
'Product description': '產(chǎn)品介紹',
'Login': '登錄',
'Register': '注冊',
'Simplified Chinese': '簡體中文'
},
...zhLocale // vuex方法,映射到中文上
}
export default cn
9、邏輯部分;
export default {
name: '',
data () {
return {
lang: 'cn', // 因為網(wǎng)站默認是中文的,默認初始化為中文
is_en: true // (因樣式問題自己單獨寫的)
}
},
methods{
handleCommand (command) {
// 點擊切換為英文
if (command === 'en') { // command 是element-ui 下拉框的用法,具體可參考官方文檔
this.lang = 'en'
this.is_en = true // 當點擊切換成英文后,此樣式生效(因樣式問題自己單獨寫的)
} else {
this.lang = 'cn'
this.is_en = false
}
this.$store.commit('switchLang', this.lang) // 這里的switchLang是調(diào)用store/index.js中mutations里的switchLang
}
},
created () {
// 點擊切換英文后調(diào)用此樣式(這里是點擊英文后頁面部分的樣式有點變化,我自己單獨寫的動態(tài)class方法)
if (this.$store.state.lang === 'en') {
this.is_en = true
} else {
this.is_en = false
}
}
// 這里主要是對應動態(tài)class部分,如果同時需要綁字兩個動態(tài)class,那么可以以數(shù)組的的方式給包裹起來
<span class="product_content" :class="[{product_content_1920:is_1920},{product_content_en:is_en}]">{{this.$t('product.productContent')}}</span>
10、最后把首頁部分全部替換成英文,然后點擊切換中英后頁面就得到英文了。
image.png
image.png