Vue.js国际化——i18n的使用

为什么需要i18n?

在不同环境针对不同的用户可能需要不同的语言环境包,常规需要接口调用的数据,可以通过请求中的language属性向后端发送请求获取对应语言的信息。而对于前端页面上的静态内容,就可以通过i18n去配置不同环境的语言包。

引入i18

1.安装依赖

npm install vue-i18n --save

2.配置方法

在项目中添加语言包文件夹,分别创建中英文语言包

在文件夹中创建main.js文件,把语言包和Vue对象引入调用

在main.js中将i18n的配置挂载到Vue对象上。

使用方法

经过配置已经可以在页面中用$t去获取语言包中配置的信息,在不同语言环境下去拿不同的语言包

 

拓展——i18n语言切换

常在一些cms的网站中出现,比如一位外国友人在中文站点需要访问外文语言包

下面是封装的一个语言切换的组件仅作参考。只针对前端语言包的切换,对于请求数据的语言切换将记录在axios的封装中。

<template>
  <div class="i18n-swith">
    <nuxt-link v-for="locale in availableLocales"
               class="switching"
               :class="$device.isMobile ? 'font-small': 'font-normal'"
               :key="locale.code"
               :to="switchLang(locale.code)"
    >
      {{ $t(`lang.${locale.code}`) }}
    </nuxt-link>
  </div>
</template>

<script>
export default {
  name: 'LangSwitch',
  data() {
    return {

    };
  },
  computed: {
    localeCode() {
      return this.$i18n.locale;
    },
    availableLocales () {
      return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale);
    }
  },
  methods: {
    switchLang(locale) {
      if (process.client) {
        this.$store.dispatch('getMenuList', { i18n: this.$i18n, route: this.$route });
        this.$store.dispatch('getFooterPages');
      }
      return this.switchLocalePath(locale);
    },
  },
};
</script>

<style lang="scss" scoped>
.i18n-swith {
  padding: 0;
  cursor: pointer;
  text-align: right;
  height: 22px;
  .switching {
    color: $base-blue;
    line-height: 22px;
    display: inline-block;
  }
}
</style>

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值