【微信小程序】组件间通信与事件-获取子组件的实例对象

1.0 前言

1.1 为何写这篇笔记

        小程序官方文档只粗略给了一段代码,让笔者找不到北,故记录下易于理解的过程,以便新手了解和使用

1.2 获取子组件实例对象的作用

        当引用了组件,且父组件使用了监听函数,当组件监听到事件发生时,可通过获取子组件实例对象,从而调用子组件中的方法

2.实例代码

2.1 index.wxml(父组件的wxml文件)

<news2 class="news"></news2>

2.2 news.js(子组件的js文件)

Component({
    
    
  methods: {
    
    
    Test01(Number){
    
    
      console.log("我收到的值是:"+Number)
    }
  }
})
  • 定义Test01方法供父组件的调用

2.3 index.js(父组件的js文件)

Page({
    
    
  getChildComponent: function () {
    
    
    const child = this.selectComponent('.news');
    console.log('子组件实例为:', child);
    child.Test01(10)
  },
  onLoad: function (options) {
    
    
    this.getChildComponent()
  },
})
  • onLoad函数用于调用getChildComponent()函数 使用this.selectComponent方法,父组件将会获取
    class 为 my-component 的子组件实例对象,即子组件的 this
    • selector匹配选择器语法
      • ID选择器:#the-id
      • class选择器(可以连续指定多个):.a-class.another-class(本文所使用的语法)
      • 子元素选择器:.the-parent > .the-child
      • 后代选择器:.the-ancestor .the-descendant
      • 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant
      • 多选择器的并集:#a-node,.some-other-nodes
  • child.Test01为子组件里的方法,相当于在子组件内this.Test01()

3.注意事项

1.获取子组件实例为空时应考虑是否显示了子组件

        笔者在使用这个方法的时候,测试用例成功了,但是具体代码获取子组件实例总是为空,摸索了好久才知道,需要wxml中使用的子组件显示出来的时候,才可以使用,如

<news  class="news" wx:if="{
    
    {true}}"></news>

是可以使用获取子组件实例的,但

<news  class="news" wx:if="{
    
    {false}}"></news>

因为不显示,就获取不到实例了

参考资料:
【小程序官方文档】
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html
https://developers.weixin.qq.com/miniprogram/dev/api/wxml/SelectorQuery.select.html

猜你喜欢

转载自blog.csdn.net/ahLOG/article/details/119257154