Vue組件設(shè)計-Sticky布局效果示例
Vue組件設(shè)計-Sticky布局
Sticky布局即為粘性定位,常見于一些重要的頁面區(qū)域在向上滾動時不會被卷起來,在CSS中可以通過設(shè)置position:sticky來實現(xiàn)這一功能,但是如果出于兼容性考慮或是一些復(fù)雜的場景,就需要我們用傳統(tǒng)的方法來實現(xiàn),以下基于Vue封裝一個組件給大家參考。
1. 效果示例

2. 組件封裝
<template>
<div :style="{height:height + 'px', zIndex: zIndex }">
<div
:class="className"
:style="{
width: width,
zIndex: zIndex,
position: position,
height: height + 'px',
top: isSticky ? stickyTop + 'px' : '',
}">
<slot>
</slot>
</div>
</div>
</template>
<script>
export default {
name: "Sticky",
props: {
stickyTop: {
type: Number,
default: 0,
},
zIndex: {
type: Number,
default: 1,
},
className: {
type: String,
default: "",
},
},
data() {
return {
position: "",
active: false,
isSticky: false,
width: undefined,
height: undefined,
};
},
mounted() {
this.height = this.$el.getBoundingClientRect().height;
window.addEventListener("scroll", this.handleScroll);
window.addEventListener("resize", this.handleResize);
},
// 組件激活時調(diào)用
activated() {
this.handleScroll();
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
window.removeEventListener("resize", this.handleResize);
},
methods: {
sticky() {
if (this.active) {
return;
}
this.active = true;
this.isSticky = true;
this.position = "fixed";
this.width = this.width + "px";
},
handleReset() {
if (!this.active) {
return;
}
this.reset();
},
reset() {
this.position = "";
this.width = "auto";
this.active = false;
this.isSticky = false;
},
handleScroll() {
// 粘性定位區(qū)域的寬度
const width = this.$el.getBoundingClientRect().width;
this.width = width || "auto";
// 粘性定位距屏幕頂部的高度
const offsetTop = this.$el.getBoundingClientRect().top;
// 如果滾動高度小于設(shè)定的定位高度
if (offsetTop < this.stickyTop) {
this.sticky();
return;
};
this.handleReset();
},
handleResize() {
if (this.isSticky) {
this.width = this.$el.getBoundingClientRect().width + "px";
}
},
},
};
</script>3. 組件使用
<template>
<div style="height:2000px;">
<div style="height:200px;background-color:green"></div>
<Sticky>
<div style="height:300px;background-color:red;line-height:300px;text-align:center;font-size:30px;">
這是定位區(qū)域
</div>
</Sticky>
</div>
</template>
<script>
import Sticky from "@/components/Sticky";
export default {
components:{
Sticky:Sticky
}
};
</script>到此這篇關(guān)于Vue組件設(shè)計-Sticky布局的文章就介紹到這了,更多相關(guān)Vue Sticky布局內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VueCli生產(chǎn)環(huán)境打包部署跨域失敗的解決
這篇文章主要介紹了VueCli生產(chǎn)環(huán)境打包部署跨域失敗的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
vue3項目如何使用樣式穿透修改elementUI默認(rèn)樣式
這篇文章主要介紹了vue3項目使用樣式穿透修改elementUI默認(rèn)樣式,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
解決vue項目中type=”file“ change事件只執(zhí)行一次的問題
這篇文章主要介紹了vue項目中解決type=”file“ change事件只執(zhí)行一次的問題,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2018-05-05
vue3+ts+Vuex中使用websocket協(xié)議方式
這篇文章主要介紹了vue3+ts+Vuex中使用websocket協(xié)議方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

