因为项目是vue2向vue3兼容的,所以npm和node版本比较低,安装最新的i18n没有效果,所以安装8.27版本的
npm install --save vue-i18n@8.27.1
安装完以后新建一个i18n的文件夹,包含一个index.js,以及其他的国际化的文件。
index.js:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import localeLib from 'element-ui/lib/locale'
import commonEn from './common/en'
import commonZh from './common/zh'
Vue.use(VueI18n)
const messages = {
en: {
...commonEn
},
zh: {
...commonZh
},
}
const i18n = new VueI18n({
locale: localStorage.getItem('language') || 'en', // 设置语种
messages, // 设置全局当地语言包,
fallbackLocale: 'zh',
numberFormats: { //设置 数字本地化
'en': {
currency: { //添加 $
style: 'currency', currency: 'USD'
}
},
'zh': {
currency: { //添加 ¥
style: 'currency', currency: 'JPY', currencyDisplay: 'symbol'
}
}
},
dateTimeFormats: {//设置 日期时间本地化
'en': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
},
'zh': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
}
}
})
// localeLib.i18n((key, value) => i18n.t(key, value))
export default i18n
其中有关于elementui的国际化暂时不考虑就先注释了,放开的话elementui的组件会有问题。
这个语言的选择是保存在localStorage里面的,也就是说如果切换语言只要修改localStorage里面的值就可以了。
具体的en.js
let common = {
'title.no': 'no'
}
export default common
main.js
添加i18n
用法:
<template>
<div class="wrap">
{{ $t('title.no') }}
</div>
</template>
模板里面直接使用
setup(props,{root}) {
onMounted(()=>{
console.log(root.$t('title.no'))
})
return {};
}
js里面在setup里面用root.$t()
注:结构$t会报错
先使用起来,后期可能会优化或者升级。