微信小程序封装组件
1,准备子组件1,准备子组件
//新建components文件夹,再建tab文件如下// (1)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>
// (2)tab.jsComponent({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.setData({tabId :tabId})//调用父组件自定义方法,传参this.triggerEvent('onTab', tabId)},}})
// (3)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,在父组件中使用```javascript// (1)index.json引入"usingComponents": {"tab":"/components/tab/tab"},
// (2)index.wxml使用<tab tabList='{{tabList}}' tabId='{{tabId}}' bind:onTab='onTab'></tab>//自定义方法 = 方法名
// (3)index.js// pages/eg-flex-one/index.jsPage({data: {tabList:[{title:'美食',id:'0'},{title:'风景',id:'1'},{title:'生活',id:'2'}],tabId:'0',}onTab(e){//得到子组件传来的参数let tabId = e.detailthis.setData({tabId:tabId})console.log(tabId)},})