微信小程序父子组件传值

本文意在说明父子组件之间的传值操作,立此贴意在加强记忆。大佬请绕行。

功能:仿微信小程序的底部tabBar,实现点击切换

实现

1.子组件 footer.wxml

<view class="footer" >
    <view class="wrap" wx:for="{{tabBar}}" bindtap="change" data-content="{{item.content}}">
        <image src="{{current === item.content?item.selectedIconPath:item.iconPath}}" />
        <text class="tab" style="color:{{current===item.content?'#00ff00':''}}">{{item.text}}</text>
    </view>
</view>

2.子组件footer.wxss

.footer{
    display: flex;
    justify-content: space-around;
    position: fixed;
    bottom: 0rpx;
    left: 0rpx;
    width: 750rpx;
    height: 150rpx;
    border-top: 1px solid #ccc;
}
.wrap{
    width: 150rpx;
    height: 150rpx;
}
.wrap image{
    display: block;
    width: 75rpx;
    height: 75rpx;
    margin-top: 10rpx;
    margin-bottom: 0rpx;
}
.wrap .tab{
    margin-left: 10rpx; 
    font-size: 12px;
}

3.子组件footer.js

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    current: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabBar:[
      {
        text:"推荐",
        content:"recommend",
        iconPath:"/images/recommend.png",
        selectedIconPath:"/images/recommend-active.png"
      },
      {
        text:"聊天",
        content:"message",
        iconPath:"/images/message.png",
        selectedIconPath:"/images/message-active.png"
      },
      {
        text:"我的",
        content:"person",
        iconPath:"/images/person.png",
        selectedIconPath:"/images/person-active.png"
      },
    ]

  },

  /**
   * 组件的方法列表
   */
  methods: {
    change(e){
      console.log(e);
      // 子组件传父组件
      this.triggerEvent("change",e.currentTarget.dataset);
    }
  }
})

4.父组件index.wxml

<cus-header title="公共标题"></cus-header>



<cus-footer current="{{currentPage}}" bindchange="handlechange"></cus-footer>

5.父组件index.json

{
  "usingComponents": {
    "cus-header": "/components/header/header",
    "cus-footer": "/components/footer/footer"
  }
}

6.父组件index.js

const app = getApp()

Page({
  data: {
   currentPage: "recommend"
  },

  onLoad: function() {
   
    },

   handlechange(e){
     console.log("e = ",e);
     this.setData({
       currentPage: e.detail.content
     })
   }

  

})

7. 效果图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值