How to pass multiple props to component in Vue


In this article, we will learn how to pass multiple props from the parent component to a child component in Vue js.

In vue, we can pass data from one component to another in the form of props.

For Example, if we want to pass name and phone no as a prop from a parent component to a child component, we pass it like this.

Parent Component:

<template>
    <student title="John" phone="55593564" />
</tempalte>

Child Component:

<template>
  <div class="student">
    Name: {{ name }} <br />
    phone: {{ phoneno }}
  </div>
</template>

<script>
export default {
  name: "Student",
  props: {
    name: {
      type: String,
    },
    phoneno: {
      type: Number,
    },
  },
};
</script>

This way of passing props to a component works well if we have one or two porps data.

However, if we have to pass multiple props (more than two) together to a component, then this above way becomes tedious.

So, if we have an object and we need to pass all its properties to the child component, we can use the v-bind without an argument (using v-bind instead of :prop-name).

Let's see with an example.

Passing multiple props as an object in Vue component.

In Parent Component:

<Student v-bind="studentObj" />

<script>
export default{
    data(){
        return{
            studentObj:{
                name:'john',
                id: 123,
                subject:'Maths',
                year: 1997
            }
        }
    }
}

Here, we have passed the student Object (studentObj) as a prop to the child component using v-bind directive.

In Child Component: (Student.vue)

<template>
  <div class="student">
    Student Id : {{ id }} <br />
    Name: {{ name }} <br />
    phone: {{ year }} <br />
    Subject : {{ subject }}
  </div>
</template>

<script>
export default {
  name: "Student",
  props: {
    id: Number,
    name: String,
    year: Number,
    subject: String,
  },
};
</script>

Once it is received, we can use it in the child component template using {{ }} .

And in the child component, we have used prop validations: String and Number. It is used to validate the correct data type of the props.

If a data-type does not match, it will show and error in the browser's console.

DEMO:


💾 Recommended Articles