VueJS 使用i18n做国际化切换中英文

1、安装

npm install vue-i18n --save

2、创建存放语言包和i18n入口文件

  a、在src下创建i18n目录

  b、在src/i18n/创建i18n.js  (入口)

  c、在src/i18n/创建langs目录存放语言包

  d、在src/i18n/langs/创建en.js(英文) 和 zh.js(中文)两个文件

  

i18n.js

i18n.js
 1 import Vue from 'vue'
 2 import locale from 'element-ui/lib/locale';
 3 import VueI18n from 'vue-i18n'
 4 //import messages from './langs'
 5 
 6 //自定义中英文包
 7 import zh from './langs/zh'
 8 import en from './langs/en'
 9 
10 //element 中英文包
11 import enLocale from 'element-ui/lib/locale/lang/en'
12 import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
13 Vue.use(VueI18n)
14 
15 const messages = {
16   en: Object.assign(en, enLocale),
17   zh: Object.assign(zh, zhLocale)
18 }
19 //从localStorage中拿到用户的语言选择,如果没有,那默认中文。
20 /*const i18n = new VueI18n({
21     locale: localStorage.lang || 'zh',
22     messages,
23 })*/
24 const i18n = new VueI18n({
25   locale: localStorage.getItem('locale') || 'en',
26   messages 
27 })
28 locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换
29 console.log('%c当前缓存语言是:'+(localStorage.getItem('locale')=='en'?'English':'中文')+'','color:#fff;background:green;padding:4px;border-radius:5px');
30 export default i18n

en.js

 1 import enLocale from 'element-ui/lib/locale/lang/en'
 2 const en = {
 3     //所有侧导航的name
 4     slideBar:{
 5         overall:'Overview',
 6         servicevolume:'Service Volume',
 7         visitvolume:'Visit Volume',
 8         users:'User Volume',
 9         multimediausage:'Multimedia Volume',
10         servicefficiency:'Service Efficiency',
11         solvedstatus:'Helpful Rate',
12         transferredrate:'Transfer Rate',
13         cast:'CSAT',
14         kgperformance:'KG Performance',
15         question:'Questions',
16         outofscopeanalysis:'Question Distribution',
17         sessionflow:'Session Flow',
18         handingtime:'Handling Time',
19         handingturns:'Handling Turns',
20         leavingstatus:'Leaving Status',
21         customerjourney:'Customer Journey',
22         download:"DownLoad"
23     },
24     
25     //所有的筛选器name
26     select:{
27         country:'Country',
28         datarange:'Date Range',
29         timeUnit:'Time Unit',
30         channel:"Channel",
31         kgLevel:"KG Level",
32         domain:"Domain",
33         intent:"Intent",
34         slot:"Order"
35     },
36 
37     //页面中图表指标 的name
38     indicatorBar:{
39         totalVisits:"Total Visits",
40         totalUsers:"Total Users",
41         helpfulRate:"Helpful Rate",
42         transferRate:"Transfer Rate",
43         CSATRate:"CSAT",
44         newUsers:"New Users",
45         repeatUser:"Repeat Users",
46         solvedCases:"Helpful Cases",
47         solvedRate:"Helpful Rate",
48         transferredCases:"Transfer Cases",
49         trnasferredRate:"Transfer Rate" 
50     },
51     
52     //页面中tab选项卡name
53     Tab:{
54         totalVolume:"Total Volume",
55         channel:"Channel Comparison",
56         user:"User Distribution",
57         userVolume:"User Volume Trend",
58         repeatUser:"Repeat User Distribution",
59         solvedRate:"Helpful Rate",
60         solvedUnsolvedQuestions:"Solved/Unsolved Questions",
61         transfered:"Transfer Rate",
62         transferedQuestion:'Transfer/Not Transfer Questions'
63     },
64     //下载页
65     download:{
66         tab:{
67             tabOne:"ChatLog Data",
68             tabTwo:"Visit Data",
69             tabThree:"User Data"
70         },
71         ele:{
72             datapickerName:"Period",
73             selectName:"Visit Access Channel",
74             until:"until"
75         },
76         btn:{
77             download:"DownLoad"
78         }
79     },
80 
81     //element 组件
82     element:{
83         loadingText:"Loading..."
84     },
85 
86     //时间单位(备用)
87     dateLabel:{
88         years:"years",
89         month:"month",
90         week:"week",
91         day:"day"
92     }
93 }
94 export default en;
英文语言包

zh.js

 1 const cn = {
 2     //所有侧导航的name
 3     slideBar: {
 4         overall: '整体概览',
 5         servicevolume: '服务数量',
 6         visitvolume: '访问量',
 7         users: '用户量',
 8         multimediausage: '输入类型',
 9         servicefficiency: '服务效果',
10         solvedstatus: '解决情况',
11         transferredrate: '转人工表现',
12         cast: '用户满意度',
13         kgperformance: '知识表现',
14         question: '问题分布',
15         outofscopeanalysis: '对话流程',
16         sessionflow: '对话流程',
17         handingtime: '解决时长',
18         handingturns: '解决轮数',
19         leavingstatus: '结束离开状态',
20         customerjourney: '用户路径',
21         download:"下载"
22     },
23 
24     //所有的筛选器name
25     select: {
26         country: '国家',
27         datarange: '时间区间',
28         timeUnit: '时间单位',
29         channel: "渠道",
30         kgLevel: "知识层级",
31         domain: "域",
32         intent: "意图",
33         slot:"排序"
34     },
35     //页面中图表指标 的name
36     indicatorBar: {
37         totalVisits: "访问总量",
38         totalUsers: "用户总量",
39         helpfulRate: "解决率",
40         transferRate: "转人工率",
41         CSATRate: "用户满意度",
42         newUsers: "新用户",
43         repeatUser: "重复访问用户",
44         solvedCases: "解决数量",
45         solvedRate: "解决率",
46         transferredCases: "转人工数量",
47         trnasferredRate: "转人工率"
48     },
49     //页面中tab选项卡name
50     Tab: {
51         totalVolume: "访问总量",
52         channel: "访问渠道对比",
53         user: "用户国家分布",
54         userVolume: "用户访问趋势",
55         repeatUser: "重复用户分布",
56         solvedRate: "解决率",
57         solvedUnsolvedQuestions: "解决/未解决的问题分布",
58         transfered: "转人工率",
59         transferedQuestion:'转人工/未转人工的问题分布'
60     },
61     //下载页
62     download:{
63         tab:{
64             tabOne:"日志下载",
65             tabTwo:"访问数据下载",
66             tabThree:"用户数据下载"
67         },
68         ele:{
69             datapickerName:"时间区间",
70             selectName:"访问渠道",
71             until:"至"
72         },
73         btn:{
74             download:"下载"
75         }
76     },
77 
78     //element 组件
79     element:{
80         loadingText:"拼命加载中..."
81     },
82 
83     //时间单位(备用)
84     dateLabel:{
85         years:"年",
86         month:"月",
87         week:"周",
88         day:"日"
89     }
90 }
91 
92 export default cn;
中文语言包

3、main.js中引用src/i18n/i18n.js入口文件

 1 //引入vue 和 router模块
 2 import Vue from 'vue'
 3 import App from './App'
 4 import router from './router'
 5 //引入element-ui
 6 import ElementUI from 'element-ui'
 7 import 'element-ui/lib/theme-chalk/index.css'
 8 
 9 import i18n from './i18n/i18n'
10 
11 Vue.use(ElementUI)
12 Vue.config.productionTip = false
13 
14 let gvm = new Vue({
15   el: '#app',
16   router,
17   i18n,
18   components: { App },
19   template: '<App/>'
20 })
main.js

4、找一个vue文件(header.vue)

a、创建模板--> 下拉组件,有中英文两个选项

 1 <template>
 2     <div class="navbar">
 3         <span>Concept Tree Engineer</span>
 4         <p></p>
 5         <el-select style=" 87px;" size="mini" v-model="value" @change="toggleLang" placeholder="请选择">
 6             <el-option
 7             v-for="item in options"
 8             :key="item.value"
 9             :label="item.label"
10             :value="item.value"
11             >
12             </el-option>
13         </el-select>
14     </div>
15 </template>
模板代码

b、创建script (配置默认为英文、配置下拉选择切换语言、配置首次进入获取用户缓存的语言进行显示)

 1 <script>
 2     export default {
 3         name: 'Navbar',
 4         data() {
 5             return {
 6                 options: [{
 7                     value: 'en',
 8                     label: 'English'
 9                 }, {
10                     value: 'zh',
11                     label: '中文'
12                 }],
13                 value: 'en'
14             }
15         },
16         mounted(){
17             //用户每次刷新页面都判断 是否缓存过 语言,缓存过的话 选择其中显示的应该是缓存的语言
18             localStorage.getItem('locale') == 'en' ? this.value = 'en' : this.value = 'zh'
19         },
20         methods: {
21             toggleLang(lang) {
22                 const loading = this.$loading({
23                     lock: true,
24                     text: this.$t("element.loadingText"),
25                     spinner: 'el-icon-loading',
26                     background: 'rgba(0, 0, 0, 0.7)'
27                 });
28                 setTimeout(function(){
29                     loading.close();
30                 },600)
31                 if(lang == 'zh') {
32                     localStorage.setItem('locale', 'zh')
33                     this.$i18n.locale = localStorage.getItem('locale')
34                 } else if(lang == 'en') {
35                     localStorage.setItem('locale', 'en')
36                     this.$i18n.locale = localStorage.getItem('locale')
37                 }
38             }
39         }
40 }
41 </script>
配置代码

总结:

  1、this.options 配置的是下拉框显示的option 和 选择后的value

     this.value 是用户选择后双向绑定的 options.[index].value

  2、toggleLang(lang):用户选择后,调用toggleLang方法,判断是 选择的是英文 还是 中文。

     如果是中文:将中文缓存起来,并且赋值给全局的i18n对象的locale。完成切换。

     如果不是:将英文缓存起来,并且赋值给全局的i18n对象的locale。完成切换。

  3、mounted():vue生命周期钩子挂载完成后,获取缓存中的语言代码,绑定给下拉的vue。作用是,根据缓存的语言代码,设置下拉选项默认显示什么。

最后:展示成果

   

  本文档意在与帮助初学者快速构建vue项目,虽没什么技术含量。但不要随意转载,如需转载保存,请署上 转载地址。谢谢配合。有问题随时交流,不怕打扰。

  

  

原文地址:https://www.cnblogs.com/wangweizhang/p/10246112.html