i18N国际化开发很麻烦,如果不是客户需求,能不搞就不搞。
此组件基于vue 2.x,vue3.0请查看官方文档
Vue配置国际化i18n开发
简单使用
配置文件
如果只是配自己的就可以了,不引入Element的组件,很简单
目录结构:建议src目录下新建i18n文件夹,配置分离
安装
按项目管理选择npm或者yarm
npm install vue-i18n
yarn add vue-i18n
先写langs文件夹下的:
Index.js
import en from './en'
import tc from './tc'
import zhcn from './zhcn'
const messages = {
en,
tc,
zhcn
}
export default messages
tc\zhcn\en,分别代表繁体中文,简体中文,英文。
内容格式是一样的,value写对应的值。如下
en.js
export default {
message: {
imageVerificationCode: 'imageVerificationCode',
imageVerificationTitle: 'Can not see clearly? Change one',
usernameInput: 'Enter username',
passwordInput: 'Enter password',
verificationCodeInput: 'Enter verification code',
verifyUsername: 'Please fill in the username',
verifyPassword: 'Please fill in the password',
verifyverifition: 'Please fill in the code',
hello: 'hello world',
success: 'success'
},
button: {
login: "Login",
logout: "Logout",
add: 'Add',
search: 'Search',
query: 'Search'
}
}
zhcn.js
export default {
message: {
imageVerificationCode: '图片验证码',
imageVerificationTitle: '看不清楚?换一张',
usernameInput: '输入用户名',
passwordInput: '输入密码',
verificationCodeInput: '输入验证码',
verifyUsername: '请填写用户名',
verifyPassword: '请填写密码',
verifyverifition: '请填写验证码',
hello: '你好,世界',
success: '操作成功'
},
button: {
login: "登录",
logout: "登出",
add: '新增',
search: '搜索',
query: '查询'
}
}
对比一下,需要改哪些很明显。
繁体中文不写了。
langs文件夹的结束。
index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
import messages from './langs'
// 通过选项创建 VueI18n 实例
const i18n = new VueI18n({
locale: 'tc',//默认语言
silentFallbackWarn: true,
messages
});
export default i18n
main.js
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
import i18n from 'i18n/index'; //这个是绝对路径,需要配置,可以使用相对路径或者加上@/变成@/i18n/index
window.vm = new Vue({
...
i18n,
render: function (h) { return h(App) },
...
}).$mount('#app')
如何使用
<h2><span>{{ $t('message.hello') }}</span></h2>
<h2><span>{{ $t('button.login') }}</span></h2>
this.$t('message.hello')
this.$t('button.login')
这样就能拿到对应的值,英文是hello world,中文就你好世界。
切换语言:
this.$i18n.locale = 'en';
this.$i18n.locale = 'zhcn';
贴出的代码都是核心代码,看个人需求绑定事件触发。。。
配置element国际化组件
基于以上的配置文件,需要修改的有
i18n文件夹下的index.js, 不是langs文件下的
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import ElementUI from 'element-ui'
Vue.use(VueI18n)
import messages from './langs'
// 通过选项创建 VueI18n 实例
const i18n = new VueI18n({
locale: 'tc',
silentFallbackWarn: true,
messages
});
Vue.use(ElementUI, {
i18n: (key, value) => i18n.t(key, value) // 在注册Element时设置i18n的处理方法
});
export default i18n
基本上就可以了。
说明:由于版本兼容的问题,element国际化不生效,
自己配置了加入内容如下:
应用于分页的插件,同样的配置方式
en.js
export default {
...
el: {
pagination: {
goto: 'Go to',
pagesize: '/page',
total: 'Total {total}',
pageClassifier: ''
},
}
}
zhcn.js
export default {
...
el: {
pagination: {
goto: '前往',
pagesize: '条/页',
total: '共 {total} 条',
pageClassifier: '页'
},
}
}