Как добавить несколько типов данных для VueJs Props? - PullRequest
0 голосов
/ 04 декабря 2018

Эта ошибка выводила меня при передаче различных значений компоненту.

enter image description here

Ответы [ 3 ]

0 голосов
/ 04 декабря 2018

В общем случае реквизиты указываются в виде массива строк, если у вас нет головной боли типа:

props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

Если вы хотите, чтобы каждая опора имела определенный тип значения.В этих случаях вы можете перечислить реквизиты как объект, где имена и значения свойств содержат имена и типы реквизитов, соответственно:

props: {
    title: String,
    likes: Number,
    isPublished: Boolean,
    commentIds: Array,
    author: Object
}

Если вы хотите использовать множественный тип, выполните следующие действия:

props: {
    value: [String, Number],
}
0 голосов
/ 05 декабря 2018

Как и предполагали другие, существует два способа определения реквизита в vuejs:

Первый

//No need to define the type with this one
props: ['myVariable', 'foo', 'something']

Второй

//With this one you can define what type the prop is and other different useful things!
props: {
  myVariable: String, //You can define the type like this
  anyOfTheFollowing: String/Object/Array, //You can also define multiple possible types
  'kebab-case-like': Function, //Since vuejs is still javascript and the property 'props' is actually an object, you can define your props like this for kebab-case. You can also just use camelCase and use the kebab-case version in your template and it will still recognize it
  customOne: MyCustomType, //You can in theory use classes you've defined aswell
  foo: { //This is another way of defining props. Like an object
    type: Number,
    default: 1, //This is why this is mostly used, so you can easily define a default value for your prop in case it isn't defined
  },
  andAnotherOne: {
    type: Array,
    default: () => [], //With Arrays, Objects and Functions you have to return defaults like this since you need to return a new reference to it for it to be used
  },
  requiredOne: {
    type: Object,
    required: true //Another use for this. When it is marked as required and it isn't defined you'll get an error in the console telling you about it
  }
}

IMO Мне нравится вторая версия, так как она открывает гораздо больше, и мне особенно нравится свойство по умолчанию.

0 голосов
/ 04 декабря 2018

Вот решение, которое я нашел.

props: {
    value: Number | String | Array
 }

или

props: {
    value: [Number,String,Array]
}
...