小程序子组件向父组件传递数据
<!- 子组件wxml -->
<view class="child">
<view class="child_item {{item.isActive===true?'active':''}}"
wx:for="test_data"
wx:key="id"
bindtap="handleTap"
data-index = {{index}}
>{{item.name}}</view>
</view>
绑定点击事件, 子组件触发父组件的自定义事件 this.triggerEvent("事件名",参数)向父组件传递参数
//子组件js
Component({
properties: {
test_data:{
type:Array,
value:[]
}
},
methods:{
handleTap(e) {
const index = e.currentTarget.dataset.index;
this.triggerEvent("handlefatherEvent",index);
}
}
})
<!-- 父组件wxml -->
<child test_data="{{testData}}" bindhandleFatherEvent="handleFatherEvent">
</child>
父组件绑定自定义事件,接收子组件传递数据
//父组件js
Page({ data:{ testData:[ {id:0,apple,isActive:true}, {id:1,banana,isActive:false}, {id:2,grape,isActive:false} ] }, handleFatherEvent(e) { const index = e.detail; let data = this.data.testData; data.forEach( (v,i)=>i===index? v.isActive=true:v.isActive=false) this.setData({testData:data}); } })
浙公网安备 33010602011771号