How to pass multiple props to component in Vue
Short article on how to pass multiple props to a component in vue using v-bind.
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.
<u>Parent Component:</u>
<template> <student title="John" phone="55593564" /> </tempalte>
<u>Child Component:</u>
<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 props data.
However, if we have to pass multiple props (more than two) together to a component, then the 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.
<u>In Parent Component:</u>
<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.
<u>In Child Component: (Student.vue)</u>
<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 an error in the browser's console.
DEMO:

Related Topics:
How to pass data from parent component to child using props in Vue
Related Posts
How to pass data from parent component to child using props in Vue
Find out how to send data from parent component to child component using props in Vue.
Execute a function from child component in Vue
Find out how we can execute a function in the parent component from the child component using emit function in Vue.
Pass multiple objects as props in Vue
Short tutorial on how to pass multiple objects as props to a child component from parent in vue using v-for directive.
How to listen for props changes in VueJS?
This article is about how to listen for prop changes in vue. We will be vuejs watcher or watch property to listen for any changes in props.
