1

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?

0

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.