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