I just discovered, don't define the properties of a component like this:
const props = defineProps({ id: Number, title: String, name: String, })
I can do this:
defineProps([ 'id', 'title', 'name', ])
This doesn't seem to require a type
declaration, but are there any downsides to doing this? vue
Do you determine the type
of each attribute yourself?
I am using script setup
.
P粉0233267732024-03-22 13:20:54
This is not just a type
declaration.
This is a prop verification function. The complete syntax is
const props = defineProps({ name: String, id: [ Number, String ], style: { type: Object, default: ()=>{ color: "red", bg-color: "white" }, validator: function (value) { return ['red', 'blue', 'green'].includes(value.color) } }, })
So the disadvantages of using only named props are:
type safety
. But even in case of typed props
it only shows console warning in development build. The advantage of using prop definition is
types
P粉2621135692024-03-22 10:11:21
The disadvantage is of course poor security.
Does vue determine the type of each property by itself? Won't
When providing an array of strings, Vue does not validate the type of the passed props at all, so if used incorrectly (which is more likely to happen, as other developers/futures you have no way of knowing what should be passed without reading the component (the rest of the code) you'll end up with some runtime error somewhere in the component, rather than a clean error/warning (or a reasonable error from the IDE) about the wrong value passed as a prop
Most of the time, you should use as many specific prop definitions as possible.