Home > database >  Declaring props in array vs array of objects
Declaring props in array vs array of objects

Time:03-26

I just found out that instead of defining the properties of a component like so:

    const props = defineProps({
        id: Number,
        title: String,
        name: String,
    })

I can do this instead:

    defineProps([
        'id',
        'title',
        'name',
    ])

This doesn't seem to require type declaration but is there any downside to doing this? Does vue determine the type of each property by itself?

I'm using script setup.

CodePudding user response:

Downside is of course less safety.

Does vue determine the type of each property by itself? No

When providing array of strings, Vue does not validate the type of passed props at all so in case of incorrect usage (which is much more likely to happen as other devs/future you are not able to tell what should be passed in without reading the rest of component's code) you end up with some runtime error somewhere in your component instead of clean error/warning about wrong value passed as prop (or a sensible error from your IDE)

You should use as much specific props definition as possible most of the time.

CodePudding user response:

Well it's not just type declaration.

It is a prop validation feature. 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 downside of using just the named props is:

  1. No type safety. But even in case of typed props it will only show console warning in development build.

Whereas the advantage of using prop definition is

  1. Multiple types for single prop
  2. Default value for a prop
  3. Custom validator function
  • Related