VueJS pass all props to child component
Parent component
<template> <div id="app"> <child-component v-bind="propsToPass"></child-component> </div></template><script> import ChildComponent from './components/child-component/child-component' export default { name: 'app', components: { ChildComponent }, data () { return { propsToPass: { name: 'John', last_name: 'Doe', age: '29', } } } }</script>
Child Component
<template> <div> <p>I am {{name}} {{last_name}} and i am {{age}} old</p> <another-child v-bind="$props"></another-child> <!-- another child here and we pass all props --> </div></template><script> import AnotherChild from "../another-child/another-child"; export default { components: {AnotherChild}, props: ['name', 'last_name', 'age'], }</script>
Another Child component inside the above component
<template> <h1>I am saying it again: I am {{name}} {{last_name}} and i am {{age}} old</h1></template><script> export default { props: ['name', 'last_name', 'age'] }</script>
Parent component
You can pass as many props as you want to child component
Child Component
Once you are satisfied with all the props, then you can use v-bind="$props"
inside your child component to retrieve all the props.
Final Result:
Done:)
In Vue 2.6+
, in addition to attributes passing,events/listeners can be also passed to child components.
Parent component
<template> <div> <Button @click="onClick">Click here</Button> </div></template><script>import Button from "./Button.vue";export default { methods:{ onClick(evt) { // handle click event here } }}</script>
Child component
Button.vue
<template> <button v-bind="$attrs" v-on="$listeners"> <slot /> </button></template>
Update [2021-08-14]:
In Vue 3, $listeners
will be removed. $attrs
will have both listeners and attributes passing to the child component.
Child component
Button.vue
<template> <button v-bind="$attrs"> <slot /> </button></template>