一、安装
1、 首先安装依赖
```javascript
npm install vue-i18n --save-dev
```
2、 在项目中引用i18n,想项目实行API和模板语法,在main.js引入
// 引入i18n国际化插件
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 注册i18n实例并引入语言文件
const i18n = new VueI18n({
locale: Cookies.get('locale') || 'zh',
messages: {
'zh': require('./assets/lang/zh'),
'en': require('./assets/lang/en')
}
})
3、之后我们创建两个js
zh.json是放中文的
{
"common": {
"home": "首页",
"public":"上市",
"Review":"评审",
"Booking":"记账",
"Development":"开发",
"exchange": "交易",
"fiat": "稳定币"
}
en.json英文版
{
"common": {
"home": "Home",
"public":"STO",
"Review":"Review",
"Booking":"Blockchain Ledger",
"Development":"Development",
"exchange": "Exchange",
"fiat": "OTC"
}
4、点击切换按钮,配合elementUI 一起完成的切换
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link market">
{{$Cookies.get('locale')=='en'?'English':'简体中文'}}<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown" style="padding: 0 10px">
<el-dropdown-item command="zh">简体中文</el-dropdown-item>
<el-dropdown-item command="en">English</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
//js
handleCommand(command) {
let _this = this
_this.$Cookies.set('locale', command) //存储在cookies中
_this.$router.go(0)
},
二、渲染模板
//vue组件模板的使用
<div>{{$t('message.zh')}}</div>
//vue组件模板数据绑定的使用
<input :placeholder="$t('message.zh')"></input>
//判断是否是中文添加class
:class="$Cookies.get('locale')=='en'?'noPadding':''"
//vue组件data中赋值的使用
data:{
msg:this.$t('message.zh');
}
getVideo() {
let that = this
let locale = that.$i18n.locale
console.log(locale)
}
三、路由与面包屑导航国际化的语法问题
router.js(路由配置文件)
{
path: '/index',
name: 'nav.Home', //直接点出对应的文字
component: (resolve) => require(['@/components/index'], resolve)
}
<div id="Breadcrumb">
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/index' }">{{$t('nav.Home')}}</el-breadcrumb-item>
/*注意{{$t(item.name)}}*/
<el-breadcrumb-item v-for="item in $route.matched" :to="{ path: item.path}">{{$t(item.name)}}</el-breadcrumb-item>
</el-breadcrumb>
</div>
最后一节引用了一位大神的方法