安装vue-i18n
1 | npm i vue-i18n -S |
创建配置文件
创建一个lang文件夹,里面再创建一个index.js
文件和一个config文件夹,index.js内容如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// http://xx.net/index?lang=en 英文
// http://xx.net/index?lang=zh 中文
const locale = location.href.indexOf('lang=en') > -1 ? 'en' : 'zh'
const i18n = new VueI18n({
locale, // 语言标识
messages: {
zh: require('./config/zh'),
en: require('./config/en')
}
});
export default i18n
定义语言文件配置
在刚刚创建的config文件夹下分别创建zh.js
和en.js
文件,内容分别如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25// zh.js
module.exports = {
header: {
navList: ['首页', '活动列表', '供需大厅','企业主页','直播专区','我的']
},
index: {
title: '直播预告'
},
footer: {
desc: '如您的浏览器不是最新版本,可能导致浏览器异常。',
}
}
// en.js
module.exports = {
header: {
navList: ['home', 'activeList', 'xx','xx','xx','my']
},
index: {
title: 'zhiboyugao'
},
footer: {
desc: 'If your browser is not up to date, it may cause a browser exception.',
}
}
另外zh.js和en.js的结构最好是按照页面和组件的模块来划分,并且字段结构要一致,懂得都懂

在main.js引入
main.js
内容如下1
2
3
4
5
6
7
8import Vue from 'vue'
import App from './App.vue'
import i18n from '@/common/lang'
new Vue({
i18n,
render: h => h(App),
}).$mount('#app')
最后怎么使用
1. 在vue文件中
1 | export default { |
2. 在模板语法中
1 | <template> |
3. 在其他的js文件中
xx.js1
2import i18n from '@/common/lang'
console.log(i18n.$t('index.title'))
以上基本能实现简单的中英文数据切换功能了