“This is the 11th day of my participation in the Gwen Challenge.
1. Provide and inject
Provide and Inject enable data transfer between nested components. Both of these functions are used in the setup function. Parent components pass data down using provide; Sub-components use inject to obtain data passed by the parent component; Note that: 1==>provide can only transfer data downward. 2==> It must be imported from vUE when provide and Inject are usedCopy the code
2. Provide and inject
We will create two components: the child component, erzi.vue, the grandchild component, Sunzi.vue. We will pass data to its children in the parent component; Both son and grandchild components will be received; And it's displayed on the viewCopy the code
3. The parent component
<template> <erzi-com></erzi-com> </template> <script lang="ts"> import ErZi from ".. /components/ErZi.vue" import {provide, ref} from "vue" export default { name:"About", components:{ 'erzi-com':ErZi }, setup(){ let giveSunziData=ref({ with:100, height:50, Bg :'pink'}) // Provide ('giveSunzi',giveSunziData)}} </script>Copy the code
The parent component passes an object to its children provide is how it is used in the setUp composite APi: provide (' shared data names ', shared values) Shared values can be strings, numbers, objects, or arrays when received by the child component; Let XXX =inject(' share data name ');Copy the code
4. Son components
<template> <div> <h2> </h2> <div> {{getFaytherData}}</div> </div> <hr/> <sun-con></sun-con> </template> <script lang="ts"> import { defineComponent, inject } from 'vue'; import SunZI from "./SunZI.vue" export default defineComponent({ name: 'ErZi', components:{ 'sun-con':SunZI }, setup(){ let getFaytherData=inject('giveSunzi'); return { getFaytherData } } }); </script>Copy the code
5. Grandchild components
<template> <div> <h2> {{getYeYeData}}</div> </div> </template> <script lang="ts"> import { defineComponent,inject } from 'vue'; export default defineComponent({ setup(){ let getYeYeData=inject('giveSunzi'); return { getYeYeData } } }); </script>Copy the code
6. Rendering
7. Can the parent component pass multiple provides?
Sometimes, our parent component may need to pass more than one Rovide; Because we want to keep the data separate. At this point, multiple Rovides need to be passed. As a matter of practice, the parent component is !!!! that can pass multiple Rovides There's nothing wrong with that; But I personally don't recommend that we do this because we can assemble multiple pieces of data at once as we pass them; It's assembled and then passed onCopy the code
8. Reference scenarios of provide and Inject
Provide and Inject are used when the parent component has a lot of data that needs to be distributed to its children.Copy the code