Vue-i18n: Able to set default value in $t like $t(key, defaultValue) or detect whether a key existed

Created on 17 Oct 2018  路  2Comments  路  Source: kazupon/vue-i18n

Just like mentioned in #12 in the end:

Is this now possible $t('key', 'default value') ?

or is there any way to detect if a key is existed?

My use case is: there are some texts (such as 'OK', 'Cancel' etc.) in a basic component which doesn't rely on vue-i18n. I would like it detect vue-i18n first, if the user doesn't use vue-i18n or doesn't define a corresponding key in vue-i18n, than it could fallback to a string which defined in this basic component. For example:

<template>
  <button>{{ t('ok', 'Yes I do!') }}</button>
</template>

<script>
export default {
  methods: {
    // Just sample code, doesn't work when `vue-i18n` installed
    t(str, fallbackStr) {
      return this.$t ? this.$t(str) : fallbackStr ? fallbackStr : str;
    }
  }
};
</script>

Thanks.

Most helpful comment

You can use with $te.
See the docs: https://kazupon.github.io/vue-i18n/api/#te

for example:

export default {
  methods: {
    t(str, fallbackStr) {
      // use `$te` and `$t
      return this.$t && this.$te
        ? this.$te(str)
          ? this.$t(str)
          : fallbackStr
        : fallbackStr
          ? fallbackStr
          : str
  }
}

The current of $t cannot retunr default value, so that doesn't look cool. 馃槀
I'll plan to improve the API I/F of $t in the future (maybe v9.0). 馃挭

All 2 comments

You can use with $te.
See the docs: https://kazupon.github.io/vue-i18n/api/#te

for example:

export default {
  methods: {
    t(str, fallbackStr) {
      // use `$te` and `$t
      return this.$t && this.$te
        ? this.$te(str)
          ? this.$t(str)
          : fallbackStr
        : fallbackStr
          ? fallbackStr
          : str
  }
}

The current of $t cannot retunr default value, so that doesn't look cool. 馃槀
I'll plan to improve the API I/F of $t in the future (maybe v9.0). 馃挭

Ah-ha, that's what I would like! 馃懟
Thank you and close it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leo108 picture leo108  路  15Comments

nchutchind picture nchutchind  路  17Comments

thelinuxlich picture thelinuxlich  路  66Comments

bonchevski picture bonchevski  路  14Comments

tvld picture tvld  路  19Comments