tab栏切换(飞书、原生小程序)
需求:
点击顶部tab栏切换,渲染不同内容。
实例:
实现思路:
1.使用 data-* 自定义属性来嵌入自定义数据,渲染时只是传递数据,不会渲染在html中。
2.自定义属性的属性值会以参数的形式伴随点击事件传递,如:
若data-id=“1”, 则e.currentTarget.dataset.id = 1
3.在js中data中定义一个status状态值,默认为1(即此时渲染的是左边的未完成),在点击事件中使status状态值和传递过来的值相等,在页面中使用if语句按条件渲染对应的页面,即可实现点击tab栏渲染对应的页面。
实现代码:
1.HTML:
<view class="container">
<view class="content">
<view class="header">
<view data-id= "1" class="left {{status === 1 ? 'active' : ''}}" bindtap="changeTab">未完成</view>
<view data-id= "2" class="right {{status === 2 ? 'active' : ''}}" bindtap="changeTab">已完成</view>
</view>
<view class="body">
<view class="con" tt:if="{{status === 1}}">
<view class="item">123</view>
</view>
<view class="con" tt:if="{{status === 2}}">
<view class="item">456</view>
</view>
</view>
</view>
</view>
2.CSS:
.container {
width: 100%;
}
.content {
display: flex;
flex-direction: column;
background-color: #ccc;
}
.header {
width: 100%;
height: 10vh;
display: flex;
justify-content: space-around;
align-items: center;
background-color: #fff;
}
.left,
.right {
color: #666666;
font-size: 16px;
padding-bottom: 18px;
}
.active {
color: #2a2a30;
border-bottom: 2px solid #007aff;
}
.body {
width: 100%;
display: flex;
flex-direction: column;
background-color: #ccc;
}
.con {
padding: 0 16px;
height: 90vh;
}
.item {
display: flex;
background-color: pink;
}
3.JS
Page({
data: {
status: 1,
},
onLoad: function () {
},
changeTab: function (e) {
console.log('e: ', e);
let status = e.currentTarget.dataset.id
this.setData({
status: Number(status)
})
}
});