// pages/wxCase/sticky/index.js Page({ data: { navList: ['正在进行', '即将开始', '已结束'], nav_type: 0,//默认选中第一个数据 isFixed: false,//是否吸顶 navTop: 0,//nav菜单距离顶部距离 }, changeType(e) { let { index } = e.currentTarget.dataset; if (this.data.nav_type == index || index == undefined) return; this.setData({ nav_type: index }) if (this.data.isFixed) { wx.pageScrollTo({ selector: '#content', duration: 0.5//滚动动指定位置需要时间 }) } }, onReady() { // 获取节点距离顶部的距离 wx.createSelectorQuery().select("#nav").boundingClientRect((rect) => { if (rect && rect.top) { this.setData({ navTop: parseInt(rect.top) }) } }).exec() }, // 监听页面滚动事件 onPageScroll(e) { let scrollTop = parseInt(e.scrollTop), isFixed = scrollTop >= this.data.navTop; if (this.data.isFixed !== isFixed) { this.setData({ isFixed }) } } }) 将这段微信小程序开发中的js文件转化为vue框架中的代码
时间: 2024-02-14 08:21:30 浏览: 22
<>
<div class="sticky">
<div class="nav" :class="{fixed: isFixed}">
<span
v-for="(item, index) in navList"
:key="index"
:class="{active: nav_type === index}"
@click="changeType(index)"
>{{ item }}</span>
</div>
<div class="content" id="content">
<!-- 页面内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
navList: ['正在进行', '即将开始', '已结束'],
nav_type: 0,
isFixed: false,
navTop: 0
};
},
methods: {
changeType(index) {
if (this.nav_type === index || index === undefined) return;
this.nav_type = index;
if (this.isFixed) {
wx.pageScrollTo({
selector: '#content',
duration: 0.5
});
}
}
},
mounted() {
wx.createSelectorQuery()
.select('#nav')
.boundingClientRect((rect) => {
if (rect && rect.top) {
this.navTop = parseInt(rect.top);
}
})
.exec();
},
onPageScroll(e) {
const scrollTop = parseInt(e.scrollTop);
const isFixed = scrollTop >= this.navTop;
if (this.isFixed !== isFixed) {
this.isFixed = isFixed;
}
}
};
</script>
<style>
.sticky {
position: relative;
.nav {
position: relative;
z-index: 10;
&.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
span {
display: inline-block;
padding: 10px 20px;
font-size: 16px;
color: #666;
cursor: pointer;
&.active {
color: #f00;
font-weight: bold;
}
}
}
.content {
margin-top: 50px;
}
}
</style>