i18n在vue项目里的使用
1.引入
npm install vue-i18n -S
2.文件结构如下
├─application 应用目录 │ ├─src 开发目录 │ │ ├─i18n 语言包目录 │ │ │ ├─en_us.json 英文 │ │ │ ├─zh_cn.json 中文 │ │ │ │ │ ├─util 模块 │ │ │ ├─i18n.js 语言包配置文件
3.为了使项目结构更清晰,我们单独在tools文件夹中新建i18n.js文件,文件内容如下
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 以下为语言包单独设置的场景,单独设置时语言包需单独引入
const messages = {
'zh_cn': require('../i18n/zh_cn'), // 中文语言包
'en_us': require('../i18n/en_us') // 英文语言包
}
// 最后 export default,这一步肯定要写的。
export default new VueI18n({
// set locale 默认显示中文
locale : (function() {
if (localStorage.getItem('lang')) {
return localStorage.getItem('lang')
} else {
return 'zh_cn'
}
})(),
messages : messages // set locale messages
})
4.然后在main.js里面全局引入并挂载
//...其他代码
//引入多语言支持
import i18n from './util/i18n'
//...其他代码
new Vue({
i18n, //挂载i18n
router,
store,
render: (h) => h(App)
}).$mount('#root')
5.在i18n目录里面的zh.js和cn.js如下
zh_cn.json
{
login:{
'title' : '软件系统',
'username' : '请输入用户名',
'password' : '请输入密码',
'login' : '登录',
'language' : '请选择语言'
},
}
en_us.json
{
login:{
'title' : 'Software system',
'username' : 'Please enter the user name',
'password' : 'Please enter your password',
'login' : 'Login',
'language' : 'Please select language'
},
}
6.这样我再组件login.vue里面就可以使用了
//template
<h3>{{$t("login.title")}}</h3>
<button @click='langToggle'>en/中</button>
//js
methods:{
langToggle(command) {
if (this.$i18n.locale === 'zh_cn') {
this.$i18n.locale = 'zh_cn'
} else if (this.$i18n.locale === 'en_us') {
this.$i18n.locale = 'en_us'
}
localStorage.setItem('lang', command)
this.$i18n.locale = command
}
}

浙公网安备 33010602011771号