Third: value transfer between generations of components
When we need to pass values between generational components based on requirements, do we just need to pass layers of props and $emit? Yes, there’s nothing wrong with doing this, but Vue provides us with a more elegant solution: $attrs and $Listeners. Let’s start by looking at how the official API defines these attributes:
$attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs: $attrs; $listener: Event listener in parent scope, passed in to internal component. To sum up, take properties and methods from the parent component and pass them to the internal component. Let’s look at how the code is implemented:
Grandfather module (outermost module)
<template> <div class="grand-father"> <h2>{{name}}</h2> <p>{{desc}}</p> <p>{{price}}</p> <child :desc="desc" :price="price" @setPrice="setPrice"/> </div></template><script>import child from '@/components/child'export default { name: 'grandfather', components: {child}, data () { return { name: 'Name in grandfather component', desc: 'We pass desc and price to the descendant component and modify the value of price in the descendant node', price: 10 } }, methods: { setPrice (val) { this.price = val } }}</script><style></style>Copy the code
Here we pass the properties and methods required by the descendant component into the Father component (the first level of nested component), followed by the code for the Father component
<template> <div> <h4>{{name}}</h4> <son v-bind="$attrs" v-on="$listeners"/> </div></template><script>import son from '@/components/grandson'export default { name: 'father', components: { son }, data () { return { name: 'Here's the parent node.' } }, methods: {}}</script><style></style>Copy the code
In the father component, use v-bind=”$attrs” to package the functions to the props node, and use V-on =”$listener” to package the methods to the props node. What’s the code of Grandson
<template> <div class="son"> <h5>{{name}}</h5> <p>{{$attrs.desc}}</p> <input type="text" @input="changePrice"> </div></template><script>export default { name: 'son'.data () { return { name: 'This is the grandchild node.' } }, methods: { changePrice (e) { this.$emit('setPrice', e.target.value) } }, created () { console.log(this.$attrs) console.log(this.$listeners) }}</script><style></style>Copy the code
With grandson, we could use $attrs to receive all the properties passed from the outermost component and use $emit to call the events that were listened to by the outermost component, so we had communication between the next generation components