Skip to content
微信小程序父子传值调方法示例代码

子组件代码如下

新建componerts目录,新建children文件夹,然后右键新建组件,组件名称为children,内容如下:

wxml代码如下

html
<button bind:tap="testFunc1">子组件调用父组件的方法不传递参数</button>
<button bind:tap="testFunc2">子组件调用父组件的方法传递参数</button>

<view>父组件传递来的数据:{{str}}</view>
<view>父组件调用子组件方法传递来的数据:{{dataStr}}</view>

js代码如下

js
// pages/components/children/children.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    str: {
      type: String, // 组件类型
      value: '默认值' // 默认值
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataStr:''
  },
  lifetimes: {
    attached: function () {
      console.log("在组件实例进入页面节点树时执行")
    },
    detached: function () {
      console.log('在组件实例被从页面节点树移除时执行')
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 向父组件发射数据不带参数
    testFunc1() {
      this.triggerEvent('childFun')
    },
    // 向父组件发射数据带参数
    testFunc2() {
      this.triggerEvent('childFun', {
        data: '带参数版本'
      })
    },
    // 子组件方法(接收父组件传递来的数据,此方法用于父组件调用使用)
    childMethod(e) {
      this.setData({
        dataStr: e || '父组件无参数传递'
      })
    }
  }
})

父组件代码如下

index.json引入子组件

js
{
  "usingComponents": {
    "children":"/pages/components/children/children"
  }
}

index.wxml使用子组件

html
<children id="myChild" bind:childFun="fartherFun" str="{{strData}}"></children>
<!-- 上面是子组件页面,下方是父组件页面 -->
<view style="width: 100vw;height: 3rpx;background-color: #cccccc;margin-bottom: 20rpx;margin-top: 20rpx;"></view>

<button bind:tap="fartherFun2">父组件修改传递给子组件的数据</button>
<button bind:tap="fartherFun3">父组件调用子组件的方法传递数据</button>
<button bind:tap="fartherFun4">父组件调用子组件的方法不传递数据</button>
<text>子组件传来的数据:{{text}}</text>

index.js

js
Page({
  data: {
    text: '',
    strData: '我是父组件传来的数据'
  },
  // 获取子组件传来的数据
  fartherFun(e) {
    this.setData({
      text: e.detail?.data || '无参数传递'
    })
  },
  // 修改传递到子组件的数据
  fartherFun2() {
    this.setData({
      strData: '我是父组件修改后的数据' + Math.random(0, 10).toFixed(2)
    })
  },
  // 调用子组件的方法带参数
  fartherFun3(){
    const child = this.selectComponent("#myChild");  
	    child.childMethod('我是父组件调用子组件方法传递的数据')
  },
  // 调用子组件的方法不带参数
  fartherFun4(){
    const child = this.selectComponent("#myChild");  
	    child.childMethod()
  }
})