您的位置:首页 > Web前端 > Vue.js

【原创】Vue 置顶组件FixedTopWrap 支持自定义内容置顶

2018-11-30 13:23 106 查看

文章目录

背景

最近项目在实现置顶功能时,由于原使用的双标签替换实现存在状态不一致的问题,所以考虑仅用单标签实现,避免状态问题。同时由于多处使用,所以简单实现了这一组件。使用上只要像

<div>
一样包裹需要被置顶的内容即可。

效果

使用示例

<template>
<div>
<fixed-top-wrap>
<div>置顶内容</div>
</fixed-top-wrap>
...
</div>
</template>

<script>
import FixedTopWrap from '@/components/FixedTopWrap';

export default {
data() {
return {};
},
components: {
FixedTopWrap,
}
};
</script>

<style scoped>
</style>

源码

<template lang="html">
<!--置顶条目父布局-->
<div id="fix-scroll-watch" ref="fixScrollWatch" class="fixScrollWatch" :style="fixStyle"> <!--用于监听滚动位置-->
<div ref="topFixBarFixed" :class="topFixBarFixed ? 'topFixBarFixed' : ''" class="fix-index"> <!--用于固定位置-->
<slot/> <!--实际内容-->
</div>
</div>
</template>

<script>
/**
* 〖Author〗 MiWi.LIN ^^^^〖E-mail〗 80383585@qq.com
* ======================================================== Copyright(c) 2018/11/23 ==
* 〖Version〗 1.0 <BR/>
* 〖Date〗 2018/11/23_下午4:31 <BR/>
* 〖Desc〗 自动固顶 <BR/>
* 〖Modify By〗 <BR/>
*/
export default {
data() {
return {
topFixBarFixed: false,
isMounted: false,
};
},
computed: {
fixStyle() {
if (this.isMounted) {
const h = this.$refs.topFixBarFixed.offsetHeight;
return { height: `${h}px` };
}
return {};
},
},
methods: {
handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
// const fix = document.querySelector('#fix-scroll-watch');
const fix = this.$refs.fixScrollWatch;
const offsetTop = fix ? fix.offsetTop : 0;
this.topFixBarFixed = scrollTop > offsetTop;
},
},
mounted() {
this.isMounted = true;
window.addEventListener('scroll', this.handleScroll);
},
destroyed() {
window.removeEventListener('scroll', this.handleScroll);
},
};
</script>

<style scoped lang="postcss">
.fixScrollWatch {
& .fix-index {
z-index: 99;
background-color: white;
}
& .topFixBarFixed {
width: 100%;
position: fixed;
top: 0;
}
}
</style>

<
1d80f
/code>

没啥新东西,主要还是监听window scroll事件和slot使用。
写此文时,搜索置顶组件,很意外看到vue滑动页面菜单栏置顶,了解到position: sticky[/code]这一style也能轻易实现,但有兼容问题,有兴趣的可以了解下position sticky的兼容

预告

小程序版无限滚动日期Tab组件:

GitHub

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: