在小程序中分类样式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)
},