This article is about parent-child component communication. If you know props but haven’t yet, take a minute to read $attrs and learn its benefits and use it in your projects.
An introduction to $attrs
Contains property bindings (except class and style) that are not recognized (and retrieved) as prop in the parent scope. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included, and internal components can be passed in via V-bind =”$attrs” — useful when creating higher-level components. From the website
$attrs can collect all attributes passed in the parent component, except those that are not defined by props in the component.
Learn to use $attrs
First we have three components, A-B-C, and then we want to pass properties from A to C. Basically, layer by layer, we pass them down through props
<div id="app">
A{{msg}}
<component-b :msg="msg"></component-b>
</div>
Copy the code
<script>
let vm = new Vue({
el: '#app',
data: {
msg: '100'
},
components: {
'ComponentB': {
props: ['msg'],
template: `<div>B<component-c :msg="msg"></component-c></div>`,
components: {
'ComponentC': {
props: ['msg'],
template: '<div>C{{msg}}</div>'
}
}
},
}
})
</script>
Copy the code
$attrs = $attrs = $attrs = $attrs = $attrs = $attrs = $attrs = $attrs = $attrs = $attrs = $attrs
<script>
let vm = new Vue({
el: '#app',
data: {
msg: '100'
},
components: {
'ComponentB': {
template: `<div>B<component-c v-bind="$attrs"></component-c></div>`,
components: {
'ComponentC': {
props: ['msg'],
template: '<div>C{{msg}}</div>'
}
}
},
}
})
</script>
Copy the code
$attrs is easy to pass through attributes and use, avoiding the pain of writing props. Props and $attrs are acceptable ways for parent and child components to communicate.