Home > Back-end >  Pass array of objects with predefined keys as props to Vue 3 component
Pass array of objects with predefined keys as props to Vue 3 component

Time:06-02

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?

CodePudding user response:

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>
  • Related