Robert Strauch
Robert Strauch

Reputation: 12896

Pass array of objects with predefined keys as props to Vue 3 component

Defining an array as props for a Vue 3 component using the Composition API is simple...

<script setup>

defineProps({
  items: {
    type: Array,
    required: true,
  },
});

</script>

Now this array should be an array of objects like the following. That's not a problem either.

[
  {
    username: "foo",
    email: "[email protected]"
  },
  {
    username: "bar",
    email: "[email protected]"
  }
]

But is there a way to define that each object in the array must contain the properties username and email? So that someone using this component's props knows what the objects must look like?

Upvotes: 1

Views: 3802

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could use the prop validator to check the array objects like:

<script setup>

defineProps({
  items: {
    type: Array,
    required: true,
    validator(val){
       let isValidObj= val.every(obj=>obj.hasOwnProperty('username') && obj.hasOwnProperty('email') )
      if(!isValidObj){
         console.warn('The object should have username and email');
         return false
       }
      return true;
    }
  },
});

</script>

Upvotes: 5

Related Questions