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

阅读: 评论:0

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

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=&#de":to="de)">{{ $t(`lang.${de}`) }}</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>

本文发布于:2024-01-28 03:57:35,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/17063854644607.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:Vue   js   i18n
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23