Value transfer between mini program custom components

Parent component passes value to child component

Method: WXML data binding

1. Parent component: directly bind the data of the parent component to the child component

//father.js

page({
	demoData:'父组件向子组件传的数据',
})

//father.wxml,
<son  fatherData='{
   
   {demoData}}' ></son>

2. Subcomponent: Receive the data of the parent component in properties

//son.js
//properties为组件的对外属性,是属性名到属性设置的映射表
//this.data.fatherData,或this.properties.fatherData的方式都可以访问到properties内的值
Component({
	properties: {
   		fatherData:{
      	type:String
    	}
  	},
  	//将父组件传递的数据在生命周期内打印出来
	attached: function () {
    	// 在组件实例进入页面节点树时执行
    	console.log('父组件传过来的数据:'+this.data.fatherData) //父组件向子组件传的数据
  	},
})

Child component passes value to parent component

Method: Custom event

trigger event

When a custom component triggers an event, you need to use the triggerEvent method to specify the event name, detail object, and event options:

	var myEventDetail = {} // detail对象,提供给事件监听函数(要传给父组件的数据)
    var myEventOption = {} // 触发事件的选项
    this.triggerEvent('myevent', myEventDetail, myEventOption)

triggerEvent options for triggering events include:

option name type Is it required? default value describe
bubbles Boolean no false Whether the event bubbles up
composed Boolean no false Whether the event can cross the component boundary. If it is false, the event will only be triggered on the node tree referencing the component and will not enter any other components.
capturePhase Boolean no false Whether the event has a capture phase
Sample code

1. Bind custom events to the child component in the wxml of the parent component

//father.wxml
//在子组件上绑定自定义事件
<son bind:sendsondata='getfatherdata'></son>

2. Trigger this event in the js of the subcomponent

//son.js
//子组件触发自定义事件,并将组件内的数据传出去
this.triggerEvent('sendsondata', '子组件内的数据', )

3. Receive the passed data in the event function within the parent component js

//father.js
methods:{
	getfatherdata(res){
		console.log('子组件传过来的数据:'+res.detial)
	}
}

Guess you like

Origin blog.csdn.net/weixin_42215897/article/details/103719159
Recommended