0
点赞
收藏
分享

微信扫一扫

微信小程序之父子组件通信

1kesou 2022-02-04 阅读 52

父组件:

<my-test1 count="{{count}}" bind:sync="syncCount" class="customA"></my-test1>
<view>父组件中,count值是{{count}}</view>
<button bindtap="getChild">获取子组件实例对象</button>
Page({
  data: {
    count:0
  },
  syncCount(e){
    this.setData({
      count:e.detail.value
    })
  },
  getChild(){
    const child = this.selectComponent('.customA')
    // console.log(child);
    // child.setData({
    //   count:child.properties.count + 1
    // })
    child.addCount()
  }
})

子组件:

<!--components/test1/test1.wxml-->
<view>子组件中,count值是{{count}}</view>
<button bindtap="addCount">+1</button>
// components/test1/test1.js
Component({
  properties: {
    count: Number
  },
  data: {
  },
  methods: {
    addCount(){
      this.setData({
        count: this.data.count + 1
      })
      this.triggerEvent('sync',{value:this.properties.count})
    }
  }
})

组件引用

//app.json
"usingComponents": {
  "my-test1":"/components/test1/test1"
}
举报

相关推荐

0 条评论