vue 动态更改vuex_使用VueX在Vue中进行简单的动态本地化

vue 动态更改vuex

More often than not your (web) application must be multilingual. There are various libraries and components to solve this problem, but in Vue the simplest solution may be VueX, the dead simple state manager we all know and love, and your app is probably already using it.

您的(网络)应用程序通常必须是多语言的。 有各种各样的库和组件来解决此问题,但是在Vue中,最简单的解决方案可能是VueX,这是我们都知道并喜欢的简单的状态管理器,您的应用可能已经在使用它。

The goal:

目标:

We want our app to be English, but when the user changes language, everything on the screen should automagically change to another language. Our app should serve strings in this language from then on. No page reloads, no relogins, nothing. Just the flip of a switch.

我们希望我们的应用程序为英语,但是当用户更改语言时,屏幕上的所有内容都应自动更改为另一种语言。 从那时起,我们的应用程序应以这种语言提供字符串。 没有页面重新加载,没有重新登录,什么都没有。 只需轻按一下开关即可。

Step 1: Define our localization strings

步骤1:定义我们的本地化字符串

The most difficult question of localization is often how to define and store thousands of strings. I use Loco, a free online service to manage internationalization (or i18n for short) in multiple languages. In Loco you can assign an Asset ID to each of your strings, then define their content in multiple languages. When you’re done, you can export your entire localization to various file formats, including JSON. I usually export it all into a single JSON file, but you can have every language as a separate one. A very simple example with two languages, English and Hungarian would look like this:

本地化最困难的问题通常是如何定义和存储数千个字符串。 我使用Loco(免费的在线服务)来管理多种语言的国际化(或简称为i18n)。 在Loco中,您可以为每个字符串分配一个资产ID ,然后以多种语言定义其内容。 完成后,您可以将整个本地化导出为各种文件格式,包括JSON。 我通常将所有内容导出到一个JSON文件中,但是您可以将每种语言都单独使用。 一个使用两种语言(英语和匈牙利语)的非常简单的示例如下所示:

"en-EN": {
       
"page-title": "My Great Application",
"login-message": "Please log in",
"login-error": "Invalid credentials"
},
"hu-HU": {
"page-title": "Az Én Nagy Alkalmazásom",
"login-message": "Lépj be",
"login-error": "Helytelen jelszó"
}

As you see, both languages have the same Asset IDs, so it’s very easy to find the translation for a string.

如您所见,两种语言都有相同的资产ID,因此很容易找到字符串的翻译。

If you add periods to the Asset IDs, Loco will break down your translations into further JSON nodes. Just type login.message and login.error instead of login-message and login-error, and this is what you’ll get upon export:

如果您在资产ID中添加句点,那么Loco会将您的翻译分解为其他JSON节点。 只需输入login.messagelogin.error而不是login-messagelogin-error ,这就是导出时得到的结果:

"en-EN": {
       
"page-title": "My Great Application",
"login": {
"message": "Please log in",
"error": "Invalid credentials"
}
}

Sometimes you need to dynamically generated strings. For such cases you can add placeholders to your localization:

有时您需要动态生成字符串。 在这种情况下,您可以在本地化中添加占位符:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值