1、组件挂载时—监听页面滚动,事件内传入回调
2、当滑动距离超过一定距离,开启fixed
3、组件销毁时,取消监听
data(){
return {
widthLength: '',
}
}
mounted() {
// 页面监听scroll事件,并传入回调
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
// 取消监听
window.removeEventListener("scroll", this.handleScroll);
},
methods:{
// 处理页面滚动
handleScroll() {
var scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
//
var offsetTop = document.querySelector(".selecter").offsetHeight;
// 吸顶效果
if (scrollTop > offsetTop) {
this.isFixed = true; // 开启吸顶
const menuWidth = this.isHeaderStick ? 0 : this.menuCollapse ? 80 : Setting.menuSideWidth;
this.widthLength = this.isMobile || !this.headerFix ? {} : {
width: `calc(100% - ${menuWidth + 48}px)`
};
} else {
this.isFixed = false; //
this.widthLength = '';
}
}
// 筛选组件
<div class="selecter" :class="{ fixed: isFixed }" :style="widthLength? widthLength:''">
<dimension-selecter @submit="selecterSubmit" :flag="flag"></dimension-selecter>
</div>
多个页面若同时要增加吸顶效果,可将handleScroll方法提取到mixins里,混入到各个组件中使用,每个组件中只需要在生命周期内监听事件即可。