微信小程序父页面传值
要实现效果:
首页点击立即团购跳转到详情页面传值商品id,详情页在选择商品规格,选择规格为组件需要将商品id同步到组件页面然后进行交互获取规格信息,但是因为setData为异步,所以会导致组件实例未获取到商品id,不能直接在组件中引用shopId=“{{shopId}}”,所以在点击选择按钮时再进行传值
下面展示一些 内联代码片
。
//首页
<button class="next" data-id="{{item.id}}" bindtap="next">立即团购</button>
//首页
next: function(e){const shopId = e.currentTarget.dataset.id;console.log("点击团购",e.currentTarget.dataset.id)wx.navigateTo({url: '/pages/view/shopDetails/shopDetails?shopId='+ shopId})
}
//商品
<view class="guige" bindtap="guigeClick"><view><text class="color">选择规格</text><text>{{guige}}</text></view><image src="/static/arrow.png" mode="heightFix" style="height:24rpx;"></image>
</view><!-- <choiceGuige id='choiceGuige' shopid=“{{shopId}}” title='选择规格' confirmText='确定' bind:confirmEvent='confirmEvent'></choiceGuige> --><choiceGuige id='choiceGuige' title='选择规格' confirmText='确定' bind:confirmEvent='confirmEvent'></choiceGuige>
//商品
guigeClick:function(){let that = this;that.choiceGuige = that.selectComponent("#choiceGuige");//组件id挂载that.choiceGuige.guige(that.data.shopId); //此处传值,guige为自定义方法,在组件中通过该方法获取shopIdthat.choiceGuige.showDialog();//组件显示
},
confirmEvent: function (e) {let shopdata = this.data.shopdata;shopdata.list = e.detail.list;this.setData({shopdata:shopdata})this.choiceGuige.hideDialog();
},
//选择规格组件
<button class='dialog-btn' catchtap='confirmEvent'><text>{{confirmText}}</text></button>
//选择规格组件
//接收父页面传过来的值然后进行处理
guige:function(obj){console.log("父页面传过来的值",obj)this.setData({shopId: obj})
},
/**
* triggerEvent 组件之间通信子传父
*/
confirmEvent() {let guigeVal = new Array(this.data.list.color[this.data.list.cindex],this.data.list.zhongliang[this.data.list.zindex], this.data.list.size[this.data.list.sindex]);let guige = {guigeVal: guigeVal}this.triggerEvent("confirmEvent",guige);
},
利用监听器(observers)实现通讯
data里面参数取值不要与properties中定义的,无需再赋予额外的点击传值
properties:{shopId:{type: Number,value: '',observer(newVal){newVal && (this.value = newVal)this.setData({shoppingId: newVal})console.log(this.data.shoppingId)}}
}
//或者
//进入组件执行方法,数据监听器
observers:{'shopId.**':function(shopId){// shopId && (this.value = shopId)console.log(shopId)let list = {color:['白色','黑色'],zhongliang:['8kg','10kg'], size:['S','M'],cindex:0,zindex:1,sindex:0}this.setData({list : list,shoppingId: shopId})}
},