Preface
In a Vue component, data from the parent component can be received through the props attribute and then used in the component. If the parent component needs to pass its data to the child component, it can be passed to the child component through props.
If you want to get the data of the pages that nest in the child component, you can use Vue's dependency injection function to achieve it. Dependency injection allows the parent component to pass some global dependencies to the child component, including data, methods, plugins, etc. Child components can get data from their parent components by accessing the $parent property of the parent component, but this approach is not too elegant and is susceptible to component hierarchy.
Here is a more elegant way to use Vue's dependency injection to get the data of the pages that nest it:
0. It is generally enough to use this.$parent
this.$
1. Define a global data object in the parent component, and save the data to be passed to the child component in this object:
export default { data() { return { globalData: { // Data to be passed to the child component someData: 'Hello world' } } } }
2. In the template of the parent component, use the provide attribute to inject global data objects into the component instance:
<template> <div> <child-component></child-component> </div> </template> <script> import ChildComponent from './'; export default { components: { ChildComponent }, data() { return { globalData: { // Data to be passed to the child component someData: 'Hello world' } } }, provide() { return { globalData: } } } </script>
3. In the child component, use the inject property to inject the global data object passed by the parent component, and then you can use this data in the child component:
<template> <div> <p>{{ }}</p> </div> </template> <script> export default { inject: ['globalData'] } </script>
In the above code, the parent component uses the provide attribute to inject global data objects into the component instance. The child component uses the inject property to inject the global data object passed by the parent component, and then it can access this data in the child component.
It should be noted that the provide and inject properties can only be used for ancestor components to pass data to descendant components, but not for child components to pass data to parent components. If you need to modify the parent component's data in the child component, you should use the event and $emit methods to implement it.
Summarize
This is the article about 4 ways to obtain the data of the vue child components. For more related contents of the vue child components to obtain the data of the parent component, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!