引用
下载依赖包: npm install vue-i18n
taps: 若项目中不兼容最新版本的vue-i18n,可以安装旧版本
语言包
在js文件中创建该项目中所使用的相关语言包;在此只举例中文和英文俩个语言包。
1.中文
在js文件夹中新建 zh.js 文件
export const m = {
menu: {
user: '用户'
}
}
2. 英文
在js文件夹中新建 en.js 文件
export const m = {
menu: {
user: 'user'
}
}
在main.js中引用
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'en',
// this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {// 引入语言包
'zh': require('./lang/zh'), // 中文语言包
'en': require('./lang/en') // 英文语言包
}
})
// 重新封装方法,方便在js中用$t来引用语言包
export function $t (args) {
return i18n.tc.call(i18n, args)
}
new Vue({
...
i18n
})
应用到项目中
- vue组件模板的使用
<div>{{$t('message.zh')}}</div>
- vue组件模板数据绑定的使用
<input :placeholder="$t('message.zh')"/>
- js
const menusArr = [{title: this.$t('m.menu.user')}]
- 语言切换方法
// 语言切换
languageChange (item) {
setStorage('locale', item)
localStorage.setItem('locale', item)
window.location.reload()
this.$t.locale = item
},