前言
最近項目因爲國際化原因使用到了多語言,因爲前端是使用vue
的,後端同學就沒有辦法幫忙做了,而我們的vue
又沒有使用服務端渲染,值得慶幸的,我們的vue
生態是良好的,我找到了vue-i18n
來做多語言的適配。
在vue
中添加多語言
- 首先我們在項目中添加
vue-i18n
的依賴包
npm install vue-i18n --save
- 然後在我們的項目中的
src
文件夾下面添加locales
文件夾,然後在文件夾中新建我們的json
格式的語言包,還有index.js
文件;目錄大致爲:
···
- src
|- locales
|- en.json
|- zh.json
|- index.js
···
- 在我們語言包中寫入相應的文字
- en.json
{
"message": {
"hello": "hello world"
}
}
- zh.json
{
"message": {
"hello": "你好世界"
}
}
- 在
index.js
中引入vue-i18n
- index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const DEFAULT_LANG = 'zh'
const LOCALE_KEY = 'localeLanguage'
const locales = {
zh: require('./zh.json'),
en: require('./en.json'),
}
const i18n = new VueI18n({
locale: DEFAULT_LANG,
messages: locales,
})
//這裏我們拋出一個setup方法,用來修改我們的語言;
//並且在這個方法中,我們把用戶選擇的語言存儲在localStorage裏面,方便用戶下次進入是直接使用上次選擇的語言
//因爲語言的不同,可能我們頁面上的樣式也會有相應的調整,所以這裏在body上加入了相應的類名,方便我們做樣式定製
export const setup = lang => {
if (lang === undefined) {
lang = window.localStorage.getItem(LOCALE_KEY)
if (locales[lang] === undefined) {
lang = DEFAULT_LANG
}
}
window.localStorage.setItem(LOCALE_KEY, lang)
Object.keys(locales).forEach(lang => {
document.body.classList.remove(`lang-${lang}`)
})
document.body.classList.add(`lang-${lang}`)
document.body.setAttribute('lang', lang)
//把當前語言設置到vue的配置裏面,方便在代碼中讀取
Vue.config.lang = lang
i18n.locale = lang
}
//設置默認語言爲中文
setup('zh')
//把i18n綁定到window上,方便我們在vue以外的文件使用語言包
window.i18n = i18n;
export default i18n
- 在
main.js
中把vue-i18n
注入到vue
- main.js
//注意,因爲我們index.js中把i18n綁定到了window,所以要在第一個引入
import i18n from './locales'
import Vue from 'vue'
import App from './App.vue'
import './common.scss'
const app = new Vue({
components: {
App
},
i18n,
render: h => h(App),
});
- 使用語言包
- 在
vue
模板中,我們直接使用$t("message.hello")
來獲取語言包變量; - 在
vue
的js
中我們使用this.$i18n.t("message.hello")
或者i18n.t("message.hello")
來獲取語言包變量; - 在
vue
以外的js
中,我們可以使用i18n.t("message.hello")
來獲取語言包變量;
- HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h3>{{$t("message.hello")}}</h3>
<a @click="change('en')">英文</a>
<a @click="change('zh')">中文</a>
</div>
</template>
<script>
import { setup } from "./../locales/index.js";
export default {
name: 'HelloWorld',
props: {
msg: String
},
mounted (){
let h = this.$i18n.t("message.hello") ;
let hh = i18n.t("message.hello")
console.log(h,hh);
},
methods:{
change (language){
setup(language)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
margin: 0 20px;
cursor: pointer;
}
</style>
自此,我們就可以在項目中愉快的使用多語言了。
在單獨文件中使用,待更新