FrameWorks/Vue

VueRouter의 Scroll Behavior 파헤치기

ABCD 2024. 8. 3.

Scroll Behavior

보통의 브라우저라면 페이지 이동시에 항상 페이지의 최상단으로 이동하는 것을 경험해 본적이 있을겁니다.
하지만, 안타깝게도 Vue에서는 이 기능이 default가 아닌데요...

우리가 이 문제를 해결하기 위해 사용할 수 있는 것이 scrollBehavior입니다.

 

선언 위치를 보실까요??

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        // return desired position
    }
})

 

위에서 인자로 사용되는 tofromNavigation Guards과 유사합니다.

 

세번째 인자인 savePosition의 경우에는 브라우저의 뒤로가기, 앞으로가기 기능을 사용시에 사용할 수 있는 인자입니다.

 

우선 스크롤이 최상단으로 이동하게 하는 동작을 만들어 보겠습니다.

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        // always scroll to top
        return { top: 0 }
    },
})

 

참 쉽죠???

이젠 특별한 설명없이 예제만 몇개 들어보겠습니다.

 

요소(#main) 선택 후 해당 요소에서 top 10

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        // always scroll to top
        return {
            //el: document.getElementById('main')
            el: '#main',
            top: 10,
        }
    },
})

 

뒤로가기 사용시 이전페이지에서 있었던 위치로 이동

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        if(savePosition) {
            return savePosition
        } else {
            return { top: 0 }
        }
    },
})

 

to의 hash값을 이용한 스크롤을 특정 요소로 자동 이동

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        if(to.hash) {
            return {
                el: to.hash,
            }
        }
    },
})

 

스크롤에 동작 smooth, instant, auto 효과를 주고 싶을 경우

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        if(to.hash) {
            return {
                el: to.hash,
                behavior: 'smooth',
            }
        }
    },
})

 

스크롤 기능을 사용하기 위해 500ms 대기 시키기

const router = createRouter({
    history: createWebHistory(),
    routes: [...],
    scrollBehavior (to, from, savePosition) {
        return new Promies((resolve, reject) => {
            setTimeout(() => {
                resolve({ left: 0, top: 0})
            }, 500)
        })
    },
})
728x90
반응형

댓글

💲 추천 글