小程序中的子组件将值传送给父组件

在小程序中分类样式tabbar写成单独的组件,在小程序首页时,点击不同的分类获取到对应的分类ID将作为参数发送给后台,点击事件写在子组件内,但是如何将得到的分类ID传到首页中获得呢?

1、在子组件的js中的点击方法中获得想要的分类ID   最重要的是this.triggerEvent('myevent',{count:id}) 方法,在this.triggerEvent中myevent是我自己定义的方法名称,第二个参数是要传递的参数

// components/w-category/w-category.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    categorys:{
      type:Array,
      value:[]
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    tabClick: function (e) {  //点击商品分类获取对应的id
      const { index } = e.currentTarget.dataset
      const { id } = this.properties.categorys[index]  
      this.triggerEvent('myevent',{count:id})
    }
  }
})

2、在父组件的wxml中使用该子组件的便签上添加 bind:myevent="getSonCount"  其中getSonCount是我自定义的方法名称

<w-category categorys="{{categorys}}" categoryWidth="{{category_box_width}}" bind:myevent="getSonCount" bind:icre="{{tabClick}}"></w-category>

3、在父组件的js文件中的methods中调用该方法,使用e.detail.count获取子组件中传过来的分类ID

getSonCount:function(e){  //获取点击的商品分类ID
    console.log(e.detail.count)
  },

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值