【蓝牙小程序】微信小程序 "父组件"调用"子组件"的"方法函数"(method)

当前在做一个蓝牙小程序的项目,将蓝牙有关的部分做成了子组件,然后页面部分是父组件。

在父组件的滑块按钮滑动的时候,希望将滑块所在的值通过蓝牙传给设备,因此需要父组件调用子组件的一个方法函数(method)

在微信小程序中,父组件可以通过 selectComponent 方法获取子组件的实例,然后调用子组件的方法。以下是具体步骤:

1. 在子组件中定义方法

首先,在子组件的 methods 中定义需要被调用的方法。

javascript
复制
// 子组件 child-component.js
Component({
  methods: {
    childMethod() {
      console.log('子组件的方法被调用了');
    }
  }
});

2. 在父组件中调用子组件的方法

在父组件的 WXML 文件中,给子组件添加一个 id 或 class,以便在父组件中通过 selectComponent 方法获取子组件的实例。

xml
复制
<!-- 父组件 parent-component.wxml -->
<child-component id="child"></child-component>
<button bindtap="callChildMethod">调用子组件方法</button>

在父组件的 JS 文件中,通过 this.selectComponent 获取子组件的实例,并调用子组件的方法。

javascript
复制
// 父组件 parent-component.js
Page({
  callChildMethod() {
    // 获取子组件实例
    const childComponent = this.selectComponent('#child');
    // 调用子组件的方法
    childComponent.childMethod();
  }
});

3. 完整示例

子组件 (child-component):

javascript
复制
// child-component.js
Component({
  methods: {
    childMethod() {
      console.log('子组件的方法被调用了');
    }
  }
});
xml
复制
<!-- child-component.wxml -->
<view>我是子组件</view>

父组件 (parent-component):

javascript
复制
// parent-component.js
Page({
  callChildMethod() {
    const childComponent = this.selectComponent('#child');
    childComponent.childMethod();
  }
});
xml
复制
<!-- parent-component.wxml -->
<child-component id="child"></child-component>
<button bindtap="callChildMethod">调用子组件方法</button>

注意事项

  • selectComponent 方法可以通过 id 或 class 选择子组件。

  • 如果子组件是通过 slot 插入的,selectComponent 可能无法直接获取到子组件实例,此时需要通过其他方式传递数据或调用方法。

通过这种方式,父组件可以方便地调用子组件的方法,实现组件间的通信。

posted @ 2025-02-18 13:14  FBshark  阅读(388)  评论(0)    收藏  举报