项目中需要自定义切换中/英文,基于vue.js,结合vue-i18n,ElementUI,以下是使用方法。
ElementUI国际化链接: http://element-cn.eleme.io/#/...
vue-i18n:https://github.com/kazupon/vu...
安装: npm install vue-i18n
vue.js+vue-i18n国际化
先不使用ElementUI,就简单的vue.js+vue-i18n使用方法:
在main.js同级建i18n新文件夹,里面新建i18n.js、langs文件夹,langs文件夹下新建en.js、cn.js;目录如下:
//i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './langs'
Vue.use(VueI18n)
//从localStorage中拿到用户的语言选择,如果没有,那默认中文。
const i18n = new VueI18n({
locale: localStorage.lang || 'cn',
messages,
})
export default i18n
//langs/index.js
import en from './en';
import cn from './cn';
export default {
en: en,
cn: cn
}
//en.js
const en = {
message: {
'hello': 'hello, world',
}
}
export default en;
//cn.js
const cn = {
message: {
'hello': '你好,世界',
}
}
export default cn;
//main.js添加下面代码
import i18n from './i18n/i18n';
window.app = new Vue({
el: '#app',
router,
store,
i18n,
template: '<App/>',
components: { App }
})
接下来是在页面中使用、切换语言。
//html:
<p>{{$t('message.hello')}}</p> // hello, world
//js切换语言
data() {
return {
lang: 'en'
}
},
methods: {
switchLang() {
this.$i18n.locale = this.lang
}
}
通过改变this.$i18n.locale的值就可以自动切换页面的语言了,en,ja,cn...等等
vue.js+vue-i18n+elementUI国际化
更改的地方不多,如下
//i18n.js
import Vue from 'vue'
import locale from 'element-ui/lib/locale';
import VueI18n from 'vue-i18n'
import messages from './langs'
Vue.use(VueI18n)
//从localStorage中拿到用户的语言选择,如果没有,那默认中文。
const i18n = new VueI18n({
locale: localStorage.lang || 'cn',
messages,
})
locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换
export default i18n
//en.js
import enLocale from 'element-ui/lib/locale/lang/en'
const en = {
message: {
'hello': 'hello, world',
},
...enLocale
}
export default en;
//cn.js
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
const cn = {
message: {
'hello': '你好,世界',
},
...zhLocale
}
export default cn;
问题总结:
1. 在html上的写法为
<p>{{$t('message.hello')}}</p> // hello, world
2. 在标签属性上的写法
<el-input :placeholder="$t('message.hello')"></el-input>
3. 在<script>js中的写法为
const hello = this.$t('message.hello')
划重点:第一二种用法是直接写在dom上使用,切换语言时会自动切换过来;但是第三种用法就不会实时刷新,这时就需要写在computed计算属性中,如下:
computed:{
hello() { return this.$t('message.hello') },
},
methods:{
this.$message.success(this.hello);
},
/*
*此种写法能够解决在js里使用多语言切换语言,没实时切换过来的问题,
*而写在标签中的不需要这样通过computed计算,因为dom挂载的数据具有双向驱动
*/