Search code examples
vue.jsvuejs3vue-composition-apivue-script-setup

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: "foo@example.com"
  },
  {
    username: "bar",
    email: "bar@example.com"
  }
]

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?


Solution

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