2

I'm using a third party multi-language package where translation values can only be obtained/used from component's template, not from component's logic (at least I can't find how to the latter).

I need to pass such translation value in some component as a default prop value:

:placeholder="{ propValue ? propValue : $t('value') }

If placeholder is explicitly specified then use that. If not, use $t('value') instead. What's the right way to write this?

I tried this in reaction to @Michael's answer:

import i18n from "@/utilities/i18n";
export default {
  data() {
    return {
      test: i18n.t('register.agreeTermsCaptionLink')
    };
  }
};

Getting this error:

_utilities_i18n__WEBPACK_IMPORTED_MODULE_7__.default.t is not a function

drake035
  • 3,955
  • 41
  • 119
  • 229

2 Answers2

0

Solution 1

Just remove brackets from prop expression: :placeholder="propValue ? propValue : $t('value')"

Sotution 2

More complicated but helps to keep templates cleaner...

where translation values can only be obtained/used from component's template, not from component's logic

With vue-i18n you can of course obtain translation directly in code by using $t function injected into your component instance like this: this.$t('key.to.translation')

Only problem is, this is not possible to use to initialize props default values because this is just not available there.

But $t in fact just returns instance function of VueI18n global object. So if you setup your VueI18n like this:

import Vue from "vue";
import VueI18n from "vue-i18n";

Vue.use(VueI18n);

const messages = {
  en: {
    messages: {
      placeholder: "Placeholder"
    }
  },
  cz: {
    messages: {
      placeholder: "Zástupný symbol :)"
    }
  }
};

export default new VueI18n({
  locale: "en",
  messages
});

You can do this to provide translation as default value of your prop:

import i18n from "../i18n";

export default {
  name: "HelloWorld",
  props: {
    placeholder: {
      type: String,
      // default: this.$t("value") - Wont work as `this` is not Vue instance
      default: i18n.t("messages.placeholder")
    }
  }
};

Demo

Michal Levý
  • 33,064
  • 4
  • 68
  • 86
  • Thanks! I don't get it, I do the same thing and I an error. See my edited question – drake035 Nov 29 '19 at 19:03
  • It's important how your `@/utilities/i18n` file looks like. Is it really same as mine example ? `export default` part is important...you need to export your `VueI18n` object... – Michal Levý Nov 29 '19 at 19:36
-3

You can set default value to prop like this:

props: {
     propValue: {
         type: String,
         default: this.$t('value')
     }
}

With that in your template you need just to assign that value like: :placeholder="propValue"

Is that what you trying to achive?

Good luck!

mare96
  • 3,749
  • 1
  • 16
  • 28