微信小程序父子之间的传值分为两个方向
*** 先声明一下:【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 });
},
有什么地方描述的不正确,请大佬评论留言,我好及时修改