【问题标题】:Translate text coming from the script using Vue-i18n使用 Vue-i18n 翻译来自脚本的文本
【发布时间】:2019-08-29 15:48:25
【问题描述】:

我安装了 vue-i18n 插件并按照tutorial 中提到的步骤进行操作。 我现在将所有可替换的标签从英语更改为我拥有本地化文件的所有语言。我的问题是我想翻译来自页面 JavaScript 部分的消息,例如错误文本或弹出的通知......等等。

例如,我的字段中有占位符,我想翻译它们,所以我的模板如下所示:

<b-form-input
        id="password"
        v-model="passwords.currentPassword"
        :placeholder="placeholders.currentPassword"
        type="password"
      />

在脚本中我将文本设置如下

data() {
return {
  placeholders: {
    //currentPassword: "Enter your current password",
    currentPassword: this.$t("changePassword.newPasswordPlaceholder"),
    newPassword: "Enter your new password",
    confirmPassword: "Confirm your new Password"
  }

我尝试了这个解决方案,但我在字段中得到的文字是:changePassword.newPasswordPlaceholder

我尝试将 i18n 作为组件调用,但失败了……有没有办法在模板 (html) 之外设置变量值?

【问题讨论】:

  • 请提供更多您想要完成的信息。如果你想从内部函数中使用它,你可以像 let text = this.$t('message.'+ yourCustomName); 一样使用它

标签: javascript vue.js localization vue-i18n


【解决方案1】:
currentPassword: this.$t("changePassword.newPasswordPlaceholder")

此代码在本地化文件中查找当前语言。首先使用键changePassword 查找json 值。如果找到,那么它会寻找键 newPasswordPlaceholder,然后如果找到它也会返回它的值。这些值必须在所有本地化文件中输入。您必须将这些行添加到 json 文件中,如下所示:

//json file where all localisation key : value pairs stored

"changePassword": {
    "newPasswordPlaceholder" : "text of password placeholder"
}

定义这些值后,您可以使用示例中描述的翻译。也不需要像代码:placeholder="placeholders.currentPassword" 中那样从对象调用。可以直接使用i18n。

:placeholder="$t('changePassword.newPasswordPlaceholder')"

【讨论】:

  • 我正是这样做的,但显然我正在更新默认创建的文件 (en.json),而我的浏览器的语言环境是 en-GB。它在德语版本中正确显示!我一直在尝试使用this-$i18n.changePassword.newPasswordPlaceholder 和其他类似的解决方案,但我还没有尝试过只使用$t
  • @j0zeft 你必须在脚本操作中使用this。但在 html 中,您需要使用 $t
猜你喜欢
  • 1970-01-01
  • 2013-08-16
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 2020-05-06
相关资源
最近更新 更多