# Inter-component Communication and Event

# Inter-component communication

There are several basic ways of communicating between components.

  • WXML data binding: For parent components to set data to specified properties of subcomponents, only JSON-compatible data can be set (starting with the base library version {% version ('2.0.9')}, and functions can be included in the data).This is covered in Component Templates and Styles .
  • Events: Used for a subcomponent to pass data to the parent component, and can pass arbitrary data.
  • If the above two methods are not sufficient, the parent component can also obtain the child component instance object through thethis.selectComponentmethod, which gives direct access to any data and methods of the component.

# Listening to incidents

Event systems are one of the main ways of communicating between components. A custom component can trigger arbitrary events, and a page that refers to the component can listen to these events.For the basic concept and usage of events, see event .

The method of listening to the custom component events is exactly the same as the method of listened to the underlying component events:

Code example:

<!-- 当自定义组件触发“myevent”事件时,调用“onMyEvent”方法 -->
<component-tag-name bindmyevent="onMyEvent" />
<!-- 或者可以写成 -->
<component-tag-name bind:myevent="onMyEvent" />
Page({
  onMyEvent: function(e){
    e.detail // 自定义组件触发事件时提供的detail对象
  }
})

# Trigger an event

When a custom component triggers an event, you need to use thetriggerEventmethod, specifying the event name, detail object, and event options:

Code example:

Preview with Developer Tool

<!-- 在自定义组件中 -->
<button bindtap="onTap">点击这个按钮将触发“myevent”事件</button>
Component({
  properties: {},
  methods: {
    onTap: function(){
      var myEventDetail = {} // detail对象,提供给事件监听函数
      var myEventOption = {} // 触发事件的选项
      this.triggerEvent('myevent', myEventDetail, myEventOption)
    }
  }
})

Options to trigger an event include:

Option Name type Is it compulsory? Default values describe
bubbles Boolean no false Is the incident a bubble?
composed Boolean no false If the event is false, the event will only be triggered on the node tree that refers to the component, and will not enter any other component
capturePhase Boolean no false Does the event have an capture phase?

For the concept of bubbling and capture phases, please read the explaination in the chapter Events .

Code example:

Preview with Developer Tool

// Page page.wxml
<another-component bindcustomevent="pageEventListener1">
  <my-component bindcustomevent="pageEventListener2"></my-component>
</another-component>
// Component another-component.wxml
<view bindcustomevent="anotherEventListener">
  <slot />
</view>
// Component my-component.wxml
<view bindcustomevent="myEventListener">
  <slot />
</view>
// Component my-component.js
Component({
  methods: {
    onTap: function(){
      this.triggerEvent('customevent', {}) // 只会触发 pageEventListener2
      this.triggerEvent('customevent', {}, { bubbles: true }) // 会依次触发 pageEventListener2 、 pageEventListener1
      this.triggerEvent('customevent', {}, { bubbles: true, composed: true }) // 会依次触发 pageEventListener2 、 anotherEventListener 、 pageEventListener1
    }
  }
})

# Get a component instance

You can callthis.selectComponentfrom the parent component to get the instance object of the child component.

Call requires passing in a match selectorselector, such as:this.selectComponent(".my-component")

SelectorDetailed syntax can be found in the selector syntax reference document .

Code example:

Preview with Developer Tool

// Parent components
Page({
  data: {},
  getChildComponent: function () {
    const child = this.selectComponent('.my-component');
    console.log(child)
  }
})

In the previous example, the parent component would acquireclassas a subcomponent instance object ofmy-component, that is, the subcomponent's``` this`。

Note: By default, components between Weixin Mini Program and a plug-in, or between different plug-ins, will not be able to obtain a component instance byselectComponent(which will return]]null)。If you want a component to be returned byselectComponentunder the above conditions, you can customize the return result (see below).

# Custom component instances get results

If you need to customize the data returned byselectComponent, you can use the built-inbehavior:wx://component-export

Support starts with the base library version {% version ('2.2.3')%}.

When using this behavior, theexportdefinition segment in the custom component is used to specify the return value when the component is called byselectComponent.

Code example:

Preview with Developer Tool

// Custom component my-component interior
Component({
  behaviors: ['wx://component-export'],
  export() {
    return { myField: 'myValue' }
  }
})
<!-- 使用自定义组件时 -->
<my-component id="the-id" />
// Parent component calls
const child = this.selectComponent('#the-id') // 等于 { myField: 'myValue' }

In the previous example, when the parent component fetches the instance ofidas a subcomponent ofthe-id, it gets the object{ myField: 'myValue' }