22

I would like to set a default property from dictionary like this:

  props: {
    title: {
      type: String,
      default: this.$t("basic.confirm"),
    },
    description: {
      type: String,
    }
  }, ...

The $t is a vue-i18n, and I would like to set my title from dictionary, if its not defined in the parent class. But I got error:

Uncaught TypeError: this.$t is not a function

Similar error If I reload without this.

Uncaught ReferenceError: $t is not defined

But If I log out this value in the mount method it works well.

Is there a solution of setting default property from the dictionary?

Thanks in advance!

LakiGeri
  • 2,046
  • 6
  • 30
  • 56

2 Answers2

38

One solution is to have the key or part of it as default props like

title: {
   type: String,
   default: "basic.confirm", //or "confirm"
 },

and in template:

<h1>{{ $t(title) }}</h1> //or $t("basic." + title)

edit: you can access $t inside function

title: {
  type: String,
  default: function () {
    return this.$t("basic.confirm")
  }
},
artoju
  • 1,612
  • 12
  • 12
-1

One solution is to have the key or part of it as default props like

 title: {
   type: String,
   default: "", 
 },

and in template:

    <h1>{{ $t(titlep) }}</h1>

and in script:

    import { useI18n } from 'vue-i18n'
    ...
    setup(props) {
      const { t }  = useI18n()
      const titlep = computed(() =>
        props.title ? props.title : t('basic.confirm')
      )
      return { titlep }
    }
weiqinl
  • 11
  • 1