如何在微信小程序写有底部滑块效果的table页
再之前的一篇文章内我写了一个js实现底部滑块的table页,顺便再记录一下小程序里如何实现该功能。
和js实现效果一样,同样是先获取每个选项的宽度和到父级左边的距离,得到底部滑块的left值,在小程序里我把他封装成了一个小组件。
具体结构如下图
组件部分(table-top)
<template>
<view class="topNav" :style="'background:#fff'">
<view class="navName">
<view :class="selectIndex==index?'navNameActive':''" :style="'color:'+(selectIndex==index?colorActive:color)+'px;'" v-for="(item,index) in titList" :key="index" @tap="changeNav(index)">
{{item}}
</view>
</view>
<view class="activeLine">
<view class="line" :style="'left:'+left+'px;background:'+lineColor"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
selectIndex:0,
left:null,
line_width:null
}
},
props: {
titList: { type: Array, default: ['标题一','标题二','标题三'] },
bg: { type: String, default: '#fff' },
lineColor: { type: String, default: '#ff0000' },
colorActive:{ type: String, default: '#ff0000' },
color:{ type: String, default: '#999' }
},
created() {
this.getLineWidth()
},
methods: {
changeNav(index){
this.selectIndex=index
this.getLef()
},
getLineWidth(){
var _this=this
const query = wx.createSelectorQuery().in(this)
query.select('.line').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function(res){
query.exec(function(res){
console.log(res);
_this.line_width=res[0].width
})
})
this.getLef()
},
getLef(){
var _this=this
const query = wx.createSelectorQuery().in(this)
query.select('.navNameActive').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(function(res){
query.exec(function(res){
var width=res[0].width
_this.left=res[0].left+(width-_this.line_width)/2
})
})
}
}
}
</script>
<style scoped>
.navName {
display: flex;
justify-content: space-around;
color: #333;
font-size: 32rpx;
font-weight: bold;
}
.activeLine{
width: 750rpx;
position: relative;
}
.activeLine .line{
position: absolute;
top:10rpx;
width: 20rpx;
height: 4rpx;
transition: all 0.5s;
border-radius: 2rpx;
}
.topNav{
padding: 30rpx 0;
}
</style>
主页面(index)
<template>
<view class="content">
<table-top :titList="titList" bg="#fff" lineColor="#ff0000" colorActive="#ff0000" color="#999" @getVal="getSendValue"></table-top>
</view>
</template>
<script>
import tableTop from '../../components/table-top.vue'
export default {
components: {
tableTop
},
data() {
return {
titList:['报名中','活动中','已结束','已报名']
}
},
onLoad() {
},
onShow() {
},
methods: {
getSendValue: function(res){
console.log("res=========",res)
}
}
}
</script>
<style>
.content{
height: 100vh;
background-color: orange;
}
</style>
如果组件内需要点击传值给主页面可以用下面方法去监听组件上的该方法获得值。
this.$emit(“getVal”,“内容”)
下面就是启动后的效果图了。
js写有底部滑块效果的table页 ——>点这里