微信小程序封装组件(二)传参

在这里插入图片描述

1,准备子组件tab

// tab.json
{
  "component": true
}
// tab.js
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  //接收父组件的参数
  properties: {
    tabList: {            
      type: Array,      
      value: []     
    },
    tabId: {            
      type: String,      
      value: '0'    
    },
  },
//组件的初始数据
  data: {},
//组件的方法列表
  methods: {
    _tabChange(e){
      let tabId =  e.currentTarget.dataset.id
     
      //调用父组件方法,传参
      this.triggerEvent('onTab', tabId)
    },
  }
})
// tab.wxml
<view class="tabBox">
  <view wx:for="{{tabList}}" wx:key='index' class="tab">
    <view class='{{item.id==tabId?"active":""}}' 
    bindtap="_tabChange" 
    data-id='{{item.id}}'>
    {{item.title}}
  </view>
  </view>
</view>
// tab.wxss
.tabBox{
  display: flex;
} 
.tab{
  width: 200rpx;
  margin-top: 20rpx;
  text-align:center;
}
.tabBox .active{
  color: red;
  font-size: 32rpx;
  font-weight: 700;
  border-bottom: 4rpx solid red;
}

2,使用

// index.json 引入
"usingComponents": {
    "tab":"/components/tab/tab"
 },
// index.wxml 使用
<tab tabList='{{tabList}}' tabId='{{tabId}}' bind:onTab='onTab'></tab>
// index.js 传数据
// pages/eg-flex-one/index.js
Page({
  data: {
    tabList:[
      {title:'美食',id:'0'},
      {title:'风景',id:'1'},
      {title:'生活',id:'2'}
    ],
    tabId:'0',
  },
  //方法
  onTab(e){
    let tabId = e.detail
    this.setData({
      tabId:tabId
    })
    console.log(tabId)
  },
})
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值