您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

使用vue-i18n让vue代码国际化

2024/2/27 18:37:26发布11次查看
这次给大家带来使用vue-i18n让vue代码国际化,使用vue-i18n让vue代码国际化的注意事项有哪些,下面就是实战案例,一起来看一下。
需求
公司项目需要国际化,点击按钮切换中文/英文
1、安装
npm install vue-i18n --save
2、注入 vue 实例中,项目中实现调用 api 和 模板语法
import vuei18n from 'vue-i18n' vue.use(vuei18n) ; const i18n = new vuei18n({   locale: 'zh-cn',  // 语言标识, 通过切换locale的值来实现语言切换,this.$i18n.locale    messages: {    'zh-cn': require('./common/lang/zh'),  // 中文语言包    'en-us': require('./common/lang/en')  // 英文语言包   } }) new vue({  el: '#app',  i18n, // 最后  router,  template: '<app/>',  components: { app } })
3、对应语言包
zh.js中文语言包:
export const lang = {  homeoverview:'首页概览',  firmoverview:'公司概述',  firmreports:'财务报表',  firmappendix:'更多附录',  firmindex:'主要财务指标',  firmanalysis:'对比分析',  firmnews:'新闻事件档案',  firmother:'其他功能', }
en.js 英文语言包:
export const lang = {  homeoverview:'home overview',  firmoverview:'firmoverview',  firmreports:'firmreports',  firmappendix:'firmappendix',  firmindex:'firmindex',  firmanalysis:'firmanalysis',  firmnews:'firmnews',  firmother:'firmother' }
4、按钮控制切换语言
this.$i18n.locale,当你赋值为‘zh-cn'时,导航栏就变成中文;当赋值为 ‘en-us'时,就变成英文:
<p class="top_btn" @click="changelangevent">中文</p>
changelangevent() {   console.log('changelangevent');   this.$confirm('确定切换语言吗?', '提示', {    confirmbuttontext: '确定',    cancelbuttontext: '取消',    type: 'warning'   }).then(() => {    if ( this.$i18n.locale === 'zh-cn' ) {     this.$i18n.locale = 'en-us';//关键语句     console.log('en-us')    }else {     this.$i18n.locale = 'zh-cn';//关键语句     console.log('zh-cn')    }   }).catch(() => {    console.log('catch');    this.$message({     type: 'info',    });   });  }
5、模板渲染
静态渲染:
<span v-text="$t('lang .homeoverview')"></span> <span>{{$t('lang .homeoverview')}}</span>
如果是element-ui 的,在要翻译的前面加上冒号
比如:label=用户姓名 就改成 :label=$t('order.username')
动态渲染:
<span class="el-dropdown-link">{{navcompany}}</span>  computed:{    navcompany:function(){     if(this.nav_company){      let str = 'lang'+this.nav_company;      return this.$t(str);     }    } },       <el-submenu v-for="(value, title1, one) in navlist" :key="one+1" :index="(one+1).tostring()">    <template slot="title">     <router-link :to="linklist[title1]">{{ gettitle(title1) }}</router-link>    </template>         </el-submenu> methods: {   gettitle(title){     let str = 'lang.'+title;     return this.$t(str);   } }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
vue组件使用slot分发内容步骤详解
怎么实现微信小程序登录鉴权
以上就是使用vue-i18n让vue代码国际化的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product