회사에서 스크롤할때 따라다니는 메뉴를 구현했다.
구글링을 했었지만 자료가 부족하여 이번 블로그를 통해 개발했던 내용을 정리하고자 한다.
맨처음에 이벤트리스너를 사용하여 스크롤 이벤트를 감지하도록 했었지만 vuetify에서 제공하는 Scroll API가 있었다.
vuetify 설치하고 사용하면 아래와 같이 사용하면됨
<template>
<div v-scroll='onScroll'>
...
</div>
</template>
<script>
methods:{
onScroll(){
...
}
}
</script>
해당기능을 구현하기 위해 필요한 내장함수들을 알아보자
js 방식 : dom에 직접 접근하여 제어
<div id='tagId'>
document.getElementById('tagId').getBoundingClientRect().top
vue 방식 : js방식과 비슷하지만 좀더 vue스럽다
<div ref='tagId'>
this.$refs.tagId.$el.getBoundingClientRect().top
topPos
를 정함window.pageXOffset
을 통해 스크롤 값이 topPos
보다 커지면 애니메이션이 시작된다.currentPos - this.topPos
통해 topPos
값을 조정함 $nextTick() 설정으로 UI가 갱신될때 오류를 방지currentPos
가 topPos
보다 작아지면 opacity가 0이돼어 메뉴바가 사라짐data(){
return{
topPos: 0,
accountInfoStyle: {
top: 0,
position: 'relative',
transition: 'ease-in-out 1.5s',
opacity: 0,
},
}
},
mounted(){
this.topPos = this.$refs.portfolio.$el.getBoundingClientRect().top
},
methods(){
onScroll() {
let currentPos = window.pageYOffset
if (currentPos > this.topPos) {
this.accountInfoStyle.opacity = 1
this.$nextTick(() => {
this.accountInfoStyle.top = currentPos - this.topPos + 'px'
})
}
else {
this.accountInfoStyle.opacity = 0
}
}
스크롤 이벤트를 제어하는데 힘들었지만 완성해서 뿌듯했다.
좀더 vue스럽게 작성할 필요가 있겠다.