search

Home  >  Q&A  >  body text

Declare props in arrays and object arrays

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? vueDo you determine the type of each attribute yourself?

I am using script setup.

P粉238433862P粉238433862274 days ago360

reply all(2)I'll reply

  • P粉023326773

    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:

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

    The advantage of using prop definition is

    1. Multiple types
    2. of a single prop
    3. Default value of props
    4. Custom validator function

    reply
    0
  • P粉262113569

    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.

    reply
    0
  • Cancelreply