Preface
- Recently, when using parent-child components, accessing parent component data and methods through this.$parent, undefined occurs.
- The actual scenario is that the parent component has a dialog pop-up box, which contains several child component form forms, and only one child component is displayed according to the identity.
- In the child component, you need to pass an ID to the data data in the parent component. Thinking of this.$parent (which is relatively simple), I don't want to use this.$emit.
- But it was found that this.$parent instance is printed, but accessing parent component data and methods are undefined
Solution
- I looked for this.$parent instance later and found that there was no data and methods of the parent component at all, and it was not an instance of the parent component.
- Because there is a layer of dialog pop-up box outside the child component, this.$parent is an element instance, this.$parent.$parent is a parent component instance.
- The child component can directly access the data method through this.$parent when there is no package in <template></template>
- When the child component is wrapped with the dialog pop-up box, accessing data and methods through this.$parent.$parent (it depends on how many layers are covered in the actual situation)
Code example
// No package is a child component accessing the parent componentconst parent = this.$parent // Access dataparent.data // Access methodparent.method // When the child component is wrapped (such as when the dialog pops up)const parent = this.$parent.$parent // Access dataparent.data // Access methodparent.method
Summarize:
After this process, I believe you have a preliminary deep impression that the data and methods of the parent component cannot be accessed by this.$parent in Vue child components, but the situation we encounter in actual development is definitely different, so we must understand its principles and never leave the essence.
This is the article about using this.$parent to access the parent component data and methods for Vue child components. This is all about this article. For more related Vue child components, use this.$parent to access the parent component content. Please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!