The vue parent component dynamically transmits values to child components.
In some project requirements, the parent component needs to dynamically transmit values to the child component. For example, I want the parent component to dynamically obtain the returned image url array through axios and then send it to the child component, the child component of the uploaded image obtains the array and then traverses and displays the image.
There are two methods,
Method 1:
When using props to pass values, pay attention to one problem. The passed values must be listened to and assigned values by watch. Otherwise, an empty array is obtained.
Parent component:
<uploadImg :width="200" :height="200" name="productImage" size="750px*750px" ref="productImage" :src-list="this.productImage"></uploadImg>
this.productImage=res.data.cover;
Here, the array returned by the background is assigned
this.productImageAnd then pass the array to the src-list attribute defined by the Child component.
Child components:
watch:{ srcList(curVal,oldVal){ if(curVal){ ; this.uploadImg=curVal; } },}
Then the child component gets the Array
Method 2:
Through the ref attribute, the parent component calls the sub-component method and transmits the array to be passed as a parameter to the sub-component. The sub-component obtains the parameter and uses
Parent component:
this.$refs.productImage.getSrcList(res.data.cover);
Child components:
getSrcList(val){ this.uploadImg=val;}
PS: Let's take a look at the vuejs dynamic component to pass data to the child component.
The props defined by the Child component can support the parent component to transmit data to the child component. The defined props can use the binding attribute in the child component label, however, if you are using a <component> dynamic component, there is no explicit sub-component tag at this time. To transmit data to the sub-component, you must bind it in <component>.
<div class="app" id="deviceready"> <component :is="currentView" :user_name.sync="user_name" :DOB.sync="DOB"></component> </div>
Components are independent of each other.
The role of a component is independent. If you want to obtain data from the component, you need to transfer the data layer by layer. That is to say, the child component can only obtain data from the direct parent component. If it is the data of the root component, then the parent component will continue to expose the pops and bind the data from the root component.