微信小程序父页面向子组件传值

微信小程序父页面传值

要实现效果:
首页点击立即团购跳转到详情页面传值商品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为自定义方法,在组件中通过该方法获取shopId
	that.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
		})
	}
},
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冷眸同学(waim)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值