Declare props in arrays and object arrays
P粉238433862
P粉238433862 2024-03-21 18:50:02
0
2
367

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粉238433862
P粉238433862

reply all(2)
P粉023326773

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
P粉262113569

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template