The method of WeChat applet calling subcomponents

  1. Obtain the child component instance through selectComponentthe method of the parent component, and then call the method defined by it. For example:
<!-- 父组件 -->
<view>
  <child-component id="myChild" />
</view>

// 在父组件中调用
const childComponent = this.selectComponent('#myChild');
childComponent.myMethod();

   2. Use directly in the child component to this.triggerEvent()trigger a custom event, and the parent component listens to the custom event and performs corresponding operations. For example:

<!-- 子组件 -->
<view>
  <button bindtap="onButtonClick">点击按钮</button>
</view>

Component({
  methods: {
    onButtonClick() {
      this.triggerEvent('customEvent', { data: '这是传递给父组件的数据' });
    }
  }
})

// 父组件中监听自定义事件
<child-component 
  bind:customEvent="onCustomEvent"
></child-component>

onCustomEvent(event) {
  console.log(event.detail.data); // 输出:这是传递给父组件的数据
}

Both of the above two methods can achieve the purpose of calling component methods, which one to choose depends on the specific situation, and the first method is recommended under normal circumstances.

Guess you like

Origin blog.csdn.net/qq_53478650/article/details/129796569