During the development process, I encountered such a scenario. I needed to request data in the old component, and the requested data needs to be used in the grand component.
The grandfather component is like this: I have a root component, there is a father component in the root component<Father/>, and there is another child component in the father component, we call it the grand component<Son/>
Seeing this scene, vuex and eventBus are a bit underused, and then I used props to pass the data to <Father/>, and then passed this value to <Son/> through props. But it seems like it feels a bit low again, so is there a better way? There is indeed! That is $attrs and $listeners.
How to use $attrs and $listeners?
- $attrs is used to pass data from the old component to the grand component.
- $listeners is used to trigger events in the grand component from the grand component.
Use of $attrs:
- In the old component(), similar to props passing values, binding the value to be passed on to the parent component.
- In the parent component, it is also similar to props to pass values, but what is passed here is not the value, but $attrs.
- In the grand component, receive props so that this data can be used in the grand component.
(It should be noted that there is no need to receive props in the parent component, as long as it is received in the grand component.)
Then the code:
//: <Father :homeInfo="homeInfo"/> //: <Son v-bind="$attrs"/> //: <template> <div class="home"> {{}} </div> </template> <script> export default { name: "Son", data() { return {}; }, props: { homeInfo: { default: Object, default: () => {}, }, }, }; </script>
Use of $listeners:
- In the old component(), bind the event.
- In the parent component, it is also similar to binding events, but what is bound here is not the specific event, but v-on="$listeners".
- In the Sun component, the ($emit) event is triggered when needed.
Then the code:
//: <Father :homeInfo="homeInfo" @update="update"/> //: <Son v-bind="$attrs" v-on="$listeners"/> //: <template> <div class="home" @click="update"> {{}} </div> </template> <script> export default { name: "Son", data() { return {}; }, props: { homeInfo: { default: Object, default: () => {}, }, }, methods: { update() { const newHome = { name: 'new' } this.$emit("update", newHome) } } }; </script>
Summarize:
In fact, $attrs and $listeners are equivalent to a transit, mainly used on the father component. The old component and the grand component are kept in use before!
This is the article about how to elegantly implement data communication of grandparent components in VUE. For more related contents of grandparent components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!