One article to understand Vue's parent-child value transfer

data sharing

In daily development, we often encounter the problem of data transmission between components. In general, the most commonly used data transmission relationship between these two relationships is:

insert image description here

The two transmission methods use different methods, which will be analyzed in detail below.

Pass value from parent to child

Sharing data from parent components to child components requires the use of custom properties. The sample code is as follows:
insert image description here

parent component

The parent component introduces the child component and registers it using

<template>
	<CommodityInfo :msg='message'></CommodityInfo>
</template>

<script>
import CommodityInfo from "./components/CommodityInfo.vue";
export default {
    
    
	components: {
    
    CommodityInfo},
	data(){
    
    
		return{
    
    
			message:'父组件'
		}
	}
}
</script>

By :msg='message'passing message to CommodityInfo,
the msg here corresponds to the method name received by the subcomponent ( so the fields must be consistent ), and the value is message

Subassembly

Subcomponents receive via props

<template>
	<div>
		<h1>父组件传递过来的值为:{
    
    {
    
     msg }}</h1>
	</div>
</template>
<script>
	export default {
    
    
  	props:['msg'],
  }
</script>

pass value from child to parent

Child components share data with parent components using custom events. The sample code is as follows:insert image description here

Subassembly

The child component transmits data to the parent component through this.$emit, here numchangeis the method name passed to the parent component ( similarly, the field must be consistent with the received one ), and this.data is the value that needs to be passed to the parent component.

<script>
export default {
    
    
	data(){
    
    
    return{
    
    
      data: '子组件穿入的数据',
    }
  },
	methods:{
    
    
		Transmit(){
    
    
			this.$emit('numchange',this.data)
		}
	}
}
</script>

parent component

The parent component @numchangetriggers getNumchange through the received value, and val is the value passed from the child component (this.data)

<template>
	<CommodityInfo @numchange='getNumchange'></CommodityInfo>
</template>

<script>
import CommodityInfo from "./components/CommodityInfo.vue";
export default {
    
    
	components: {
    
    CommodityInfo},
	data(){
    
    
		return{
    
    
			numchange:''
		}
	},
	methods:{
    
    
		getNumchange(val){
    
    
			this.numchange = val
		}
	}
}
</script>

Guess you like

Origin blog.csdn.net/weixin_44748171/article/details/129863651