Vue Router로 앵커로 스크롤

Dec 05 2020

vuejs에서 다음으로 이동하려면 앵커 링크 설정이 필요합니다.

<h1 id="apply">Test anchor</h1>

다음은 작동하지만 URL을 http : // localhost : 8080 / # / apply로 변경합니다.

<a href="#apply" class="btn btn-primary mt-3">Apply Now</a>

그런 다음 페이지를 새로 고치면 어디로 가야할지 모릅니다.

다음은 나에게도 작동하지 않습니다. #apply로 드롭되지도 않습니다.

<router-link to="/careers/job-1#apply">test</router-link>

vuejs 라우팅으로 앵커 링크를 어떻게 설정합니까?

답변

1 Dan Dec 05 2020 at 07:51

개체에 pathhash속성을 추가 to합니다.

<router-link :to="{ path: '/careers/job-1', hash: '#apply' }">test</router-link>

scrollBehavior라우터 정의에 추가 하십시오.

const router = new VueRouter({
  ...
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash,
        behavior: 'smooth'
      };
    }
    return { x: 0, y: 0 };  // Go to the top of the page if no hash
  },
  ...
})

이제 behavior해시로 정의 된 앵커로 스크롤해야합니다 ( 해시 속성 을 제거하지 않는 한 부드럽게 ).