# 國際化
本項目集合了國際化 i18n 方案。通過[vue-i18n](https://github.com/kazupon/vue-i18n)而實現。
由于本項目 ui 框架使用了`element`,所以國際化的同時也要將其國際化。[完整代碼](https://github.com/PanJiaChen/vue-element-admin/blob/master/src/lang/index.js)。 同時將當前`lang`語言存在`cookie`之中,為了下次打開頁面能記住上次的語言設置。
# [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/i18n.html#%E5%85%A8%E5%B1%80-lang)全局 lang
代碼地址:[@/lang](https://github.com/PanJiaChen/vue-element-admin/tree/master/src/lang)目前配置了英文和中文兩種語言。
同時在`@/lang/index.js`中引入了`element-ui`的語言包
**使用:**
~~~
// $t 是 vue-i18n 提供的全局方法,更多信息請查看其文檔
$t('login.title')
~~~
# [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/i18n.html#%E5%BC%82%E6%AD%A5-lang)異步 lang
有一些某些特定頁面才需要的 lang,比如`@/views/i18n-demo`頁面
~~~
import local from './local'
this.$i18n.mergeLocaleMessage('en', local.en)
this.$i18n.mergeLocaleMessage('zh', local.zh)
~~~
# [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/i18n.html#js-%E4%B8%AD%E4%BD%BF%E7%94%A8-t)js 中使用 $t
如果你使用如`select`組件,它的值是通過`v-for`而來,如:
~~~
<el-select v-model="value">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"/>
</el-select>
~~~
~~~
this.options = [
{
value: '1',
label: this.$t('i18nView.one')
},
{
value: '2',
label: this.$t('i18nView.two')
},
{
value: '3',
label: this.$t('i18nView.three')
}
]
~~~
這種情況下,國際化只會執行一次,因為在 js 中的`this.options`只會在初始化的時候執行一次,它的數據并不會隨著你本地`lang`的變化而變化,所以需要你在`lang`變化的時候手動重設`this.options`。
~~~
export default {
watch: {
lang() {
this.setOptions()
}
},
methods: {
setOptions() {
this.options = [
{
value: '1',
label: this.$t('i18nView.one')
},
{
value: '2',
label: this.$t('i18nView.two')
},
{
value: '3',
label: this.$t('i18nView.three')
}
]
}
}
}
~~~
# [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/i18n.html#%E7%A7%BB%E9%99%A4%E5%9B%BD%E9%99%85%E5%8C%96)移除國際化
在`src/main.js`中移除`import i18n from './lang'`并且刪除`src/lang`文件夾。
并在`src/layout/components/Levelbar`、`src/layout/components/SidebarItem`、`src/layout/components/TabsView`等文件夾中 移除`this.$t('route.xxxx')`使用國際化的方式。
在v4.1.0+版本之后,默認 master 將不再提供國際化。因為大部分用戶其實是用不到國際化的,但移除國際化工作量又相當的大。
如果你有國際化需求的請使用[i18n 分支](https://github.com/PanJiaChen/vue-element-admin/tree/i18n),它與 master 同步更新。