小程序父子组件传值

目前自学微信小程序,为了加深印象,纯属记录一下,大家有更多的解决方案希望不吝赐教,万分感谢
需求:
父组件给子组件传入数据,子组件循环渲染出来,点击将index传递给父组件,父组件改变tabs数据

// 父组件list数据
    tabs: [{
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],

父组件传递tabs给子组件

//父组件
<tabs tabs="{{tabs}}"></tabs>

子组件接收

//tabs.js文件
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabs:Array,
  },
})

子组件循环处理父组件传过来的数据

<view class="">
    <view class="top">
        <view 
        class="top_list {{item.isActive?'active':''}}" 
        wx:for="{{tabs}}" 
        wx:key="id" 
        bindtap="listIndex" 
        data-index="{{index}}">
            {{item.value}}
        </view>
    </view>
</view>

子组件点击不同的循环项,将下标传递给父组件

Component({
  properties: {
    tabs:Array,
  },
  methods: {
    listIndex(e){
      const {index} = e.currentTarget.dataset
      //利用this.triggerEvent将index传递给父组件,并且执行父组件中listIndex方法
      this.triggerEvent("listIndex",{index})
    }
  }
})

父组件执行listIndex方法

//需要在自定义方法前面加上'bind'
<tabs tabs="{{tabs}}" bindlistIndex="listIndex"></tabs>

父组件JS文件

import {
  request
} from '../../request/index.js'
Page({
  data: {
    // 父组件list数据
    tabs: [{
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
  },
  // 获取子组件传来的下标修改数据
  listIndex(e) {
    const {index} = e.detail
    const tabs = JSON.parse(JSON.stringify(this.data.tabs))
    tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false)
    this.setData({
      tabs
    })
  }
})

最后效果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值