Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs default properties set from vue-i18n

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!

like image 738
LakiGeri Avatar asked Nov 06 '18 11:11

LakiGeri


People also ask

How do I change my locale Vue i18n?

locale is bound with v-model , you can switch it by selecting the option of the select element, which sets its value to $i18n. locale . As you can see, the global scope is very useful because it allows you to switch the messages displayed in the UI for all components of the application at once.

Are Vue props required by default?

All props are optional by default, unless required: true is specified.

How does Vue i18n work?

Vue I18n plugs into your Vue apps and provides you with translation file management, message formatting, date and number formatting, and more to boot. We'll fill in the gaps that the library leaves so that you can have a robust i18n cookbook for your Vue apps.

How does Vue implement localization?

You can put locale files compatible with vue-i18n in a locales folder at the root of your plugin. They will be automatically loaded into the client when the project is opened. You can then use $t to translate strings in your components and other vue-i18n helpers.


1 Answers

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")
  }
},
like image 57
artoju Avatar answered Oct 12 '22 00:10

artoju