本文意在说明父子组件之间的传值操作,立此贴意在加强记忆。大佬请绕行。
功能:仿微信小程序的底部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. 效果图