小程序经常会出现选项卡和全屏选项卡,这里写一下我的布局,以便日后使用。
1.创建选项卡组件
我们先创建一个components文件夹和navlist的组件
navlist的html:
<view class='nav-box'>
<view bindtap='clicnav' data-index="{{index}}" wx:for="{{navdata}}" wx:key="{{index}}" class='nav-list {{navindex === index?"clicknav":""}}'>
{{item.text}}
</view>
</view>
navlist的js:
// components/navbar/index.js
const App = getApp();
Component({
/**
* 组件的属性列表
*/
properties: {
//接收页面传过来的选项卡标签内容
navdata: {
type: Array,
value: []
},
//介绍swiper当前页面数值用于滑动swiper时改动选项卡的显示
current: {
type: Number,
//当父页面current值改动时触发num方法
observer: 'num',
}
},
/**
* 组件的初始数据
*/
data: {
//默认选择第一个
navindex:0,
},
attached(){
console.log(this.data.navdata);
},
/**
* 组件的方法列表
*/
methods: {
//选项卡的点击事件
clicnav(e){
//index 为选项卡的data-index参数
let index = e.currentTarget.dataset.index;
//赋值给navindex以改变点击表签的颜色
this.setData({
navindex: index
});
var that = this;
//将值传给父页面,让父页面改变swiper的当前轮播
var myEventDetail = { index: index } // detail对象,提供给事件监听函数
this.triggerEvent('myevent', myEventDetail) //myevent自定义名称事件,父组件中使用
},
num(num) {
//当父页面current值改动时修改navindex的值
this.setData({
navindex: num
});
}
}
})
navlist的json:
{
"component": true,
"usingComponents": {}
}
navlist的css:
/* components/navlist/navlist.wxss */
.nav-box{
width: 100%;
height: 100rpx;
display: flex;
}
.nav-list{
flex: 1;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 32rpx;
color: #000000;
box-sizing: border-box;
border-bottom: 2rpx solid #c4c4c4;
}
.clicknav{
border-bottom: 2rpx solid #e74a45;
color: #e74a45;
}
2.index页面调用组件
index页面调用选项卡组件并配合swiper滑动
index的html:
<view id="navheight">
<navlist bind:myevent="toggleToast" navdata="{{navdata}}" current="{{current}}"></navlist>
</view>
<swiper style='height:{{swiperHeight}}' current="{{navindex}}" bindchange="navchange">
<swiper-item>
<scroll-view style='width:100%;height:100%;background-color:green;' scroll-y>
我是第一页
</scroll-view>
</swiper-item>
<swiper-item>
<scroll-view style='width:100%;height:100%;background-color:yellow;' scroll-y>
我是第二页
</scroll-view>
</swiper-item>
<swiper-item>
<scroll-view style='width:100%;height:100%;background-color:blue;' scroll-y>
我是第三页
</scroll-view>
</swiper-item>
</swiper>
index的js:
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
//传给选项卡的标签内容
navdata: [{
text: "个人信息"
}, {
text: "个人评价"
}, {
text: "项目历史"
}],
navindex: 0,
current: 0,
swiperHeight: 0,
},
onLoad: function () {
let _this = this;
// 计算siiper到手机底部的高度赋值给swiper的height
wx.createSelectorQuery().select('#navheight').boundingClientRect(function (rect) {
wx.getSystemInfo({
success(res) {
_this.setData({
swiperHeight: (res.windowHeight - rect.bottom) + "px"
});
}
})
}).exec()
},
// 获取子组件信息
toggleToast(e) {
let index = e.detail.index;
this.setData({
navindex: index
});
},
// 滑动轮播事件
navchange(e) {
this.setData({
current: e.detail.current
});
}
})
index的json:
{
"usingComponents": {
"navlist": "./components/navlist/navlist"
}
}