[微信小程序]----父子之间的传值

微信小程序父子之间的传值分为两个方向
*** 先声明一下:【goods-list】 是父组件 ,在这个组件中引入了子组件【 goods-card】***
1-父组件先子组件传值

使用的是属性绑定,在子组件的xxx.js中使用properties接收父组件传过来的值
父组件的wxml文件内容如下
<view class="goods-list-wrap wr-class" id="{{independentID}}">
	<block wx:for="{{goodsList}}" wx:for-item="item" wx:key="index">
		<goods-card
		  id="{{independentID}}-gd-{{index}}"
		  data="{{item}}"
		  // id data 都是子组件 goods-card的属性
		  currency="{{item.currency || '¥'}}"
		  thresholds="{{thresholds}}"
		  class="goods-card-inside"
		  data-index="{{index}}"
		  bind:thumb="onClickGoodsThumb"
		  bind:click="onClickGoods"
		  bind:add-cart="onAddCart"
		/>
	</block>
</view>

子组件的xxx.js文件中定义的properties如下
  properties: {
    id: {
      type: String,
      value: '',
      observer(id) {
        this.genIndependentID(id);
        if (this.properties.thresholds?.length) {
          this.createIntersectionObserverHandle();
        }
      },
    },
    data: {
      type: Object,
      observer(data) {
        if (!data) {
          return;
        }
        let isValidityLinePrice = true;
        if (data.originPrice && data.price && data.originPrice < data.price) {
          isValidityLinePrice = false;
        }
        this.setData({ goods: data, isValidityLinePrice });
      },
    },
}

2-子组件向父组件传值

使用的是自定义事件传值父组件通过自定义事件中的事件对象e来接收子组件传递过来的值.如下代码
父组件的wxml文件如下
<view class="goods-list-wrap wr-class" id="{{independentID}}">
	<block wx:for="{{goodsList}}" wx:for-item="item" wx:key="index">
		<goods-card
		  id="{{independentID}}-gd-{{index}}"
		  data="{{item}}"
		  currency="{{item.currency || '¥'}}"
		  thresholds="{{thresholds}}"
		  class="goods-card-inside"
		  data-index="{{index}}"
		  bind:thumb="onClickGoodsThumb"
		  bind:click="onClickGoods"
		  //上面的  bind:click="onClickGoods"  中的  [ click ] 
		  //就是下面子组件xxx.文件中   this.triggerEvent('click', { goods: this.data.goods });  
		  //中的click
		  bind:add-cart="onAddCart"
		/>
	</block>
</view>
父组件的xxx.js文件,如下
  methods: {
    onClickGoods(e) {
      // [ e ]就是下面子组件xxx.文件中 this.triggerEvent('click', { goods: this.data.goods });
      //的 { goods: this.data.goods }
      console.log(' <goods-list 中的 onClickGoods方法被触发!!!!!!');
      const { index } = e.currentTarget.dataset;
      this.triggerEvent('click', { ...e.detail, index });
    },

子组件的xxx.js文件,如下
  methods: {
    clickHandle() {
      console.log('<goods-card 的clickHandle被触发');
      this.triggerEvent('click', { goods: this.data.goods });
    },



在这里插入图片描述

有什么地方描述的不正确,请大佬评论留言,我好及时修改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值