Translate text coming from the script using Vue-i18n

时间:2019-04-08 13:16:06

标签: javascript vue.js localization vue-i18n

I installed the vue-i18n plugin and followed the steps mentioned in this tutorial. I have now all tags that are replaceable changed from English, to all languages to which I have localization files. My problem is that I want to translate messages that come from the JavaScript part of the page, for example error texts or notifications that pop up... etc.

For example, I have placeholders in my fields, and I wanted to translate them, so my template looks like this:

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

in the script I set the text as follows

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

I tried this solution but the text I get in the field is:changePassword.newPasswordPlaceholder

I tried calling i18n as a component but I failed... is there a way to set the variable values outside of the template (html)?

1 个答案:

答案 0 :(得分:1)

currentPassword: this.$t("changePassword.newPasswordPlaceholder")

This code looking inside localization file for current language. There first looking for json value with the key changePassword. If it find then it will look for the key newPasswordPlaceholder then if it found it also will return the value of it. These values must be typed inside of all localization files. You must add these lines into json file as below to work as you want:

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

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

After defining these values you can use translation as you described in your example. Also there is no need to call from object as in your code :placeholder="placeholders.currentPassword". You can use i18n directly.

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