实现效果
当我在首页和原创两个菜单之间切换的时候,下面显示不同的内容
父组件wxml
<Tabs tabsss="{{tabs111}}" bind:itemChange="handle_itemChange" class="Tabs"> <block wx:if="{{tabs111[0].isActive}}">哈哈哈</block> <block wx:elif="{{tabs111[1].isActive}}">嗯嗯嗯</block> <block wx:elif="{{tabs111[2].isActive}}">呃呃呃</block> <block wx:else="{{tabs111[3].isActive}}">嘿嘿嘿</block> </Tabs>
父组件js
Page({ /** * 页面的初始数据 */ data: { tabs111: [ { id: 0, name: "首页", isActive: true }, { id: 1, name: "原创", isActive: false }, { id: 2, name: "分类", isActive: false }, { id: 3, name: "关于", isActive: false } ] }, // 自定义事件,用来接收子组件传递的数据的 handle_itemChange(e) { console.log(e) const index = e.detail // console.log(index) let tabs = JSON.parse(JSON.stringify(this.data.tabs111)) tabs.forEach((item, index111) => { index111 === index ? item.isActive = true : item.isActive = false }) // 重新赋值 this.setData({ tabs111: tabs }) }, onl oad: function (options) { } })
子组件 Tabs.wxml
<view class="tabs"> <view class="tabs_title"> <!-- data-index 自定义属性事件传参 --> <view wx:for="{{tabsss}}" wx:key="id" class="title_item {{item.isActive?'active':''}}" bindtap="_handle_item_tap" data-index="{{index}}" > {{item.name}} </view> </view> <view class="tabs_content"> <slot></slot> </view> </view>
子组件Tabs.js
Component({ properties: { tabsss: { type: Array, value: [] } }, data: { }, methods: { _handle_item_tap(e) { const index222 = e.currentTarget.dataset.index this.triggerEvent("itemChange",index222) } } })
子组件Tabs.wxss
.tabs_title { display: flex; padding: 10rpx; } .title_item { display: flex; flex:1; justify-content: center; align-items: center; } .active { color: red; border-bottom: 5rpx solid currentColor; }