[Vue.js] vue-router - 프로그래밍 방식 내비게이션

☁️ yeyo·2022년 1월 16일
0

vue-router

목록 보기
3/5
post-thumbnail

<router-link>를 사용해 선언적 바익으로 내비게이션을 만드는 방법 외에도 프로그래밍 방식으로 내비게이션을 만들 수 있다.

1. 다른 URL로 이동

(= window.history.pushState)

선언적 방식

<router-link :to="...">	

프로그래밍 방식

router.push(...)

router.push()는 다양한 인자를 매개변수로 가질 수 있다.

// 문자열 경로
router.push('/users/eduardo')

// 객체 경로
router.push({ path: '/users/eduardo' })

// 라우터가 url을 빌드할 수 있도록 명명된 경로
router.push({ name: 'user', params: { username: 'eduardo' } })

// 쿼리 사용 예시, 결과 /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } })

// 해시 사용 예시, 결과 /about#team
router.push({ path: '/about', hash: '#team' })

작성 시 주의 사항

  • path와 params는 함께 사용할 수 없다.
const username = 'eduardo'
// url 수동 작성(인코딩 직접 처리해야 함)
router.push(`/user/${username}`) // -> /user/eduardo
// path와 수동 url 조합
router.push({ path: `/user/${username}` }) // -> /user/eduardo
// 가능하면 name과 params를 사용해 자동 url 인코딩을 활용하는 것이 좋다.
router.push({ name: 'user', params: { username } }) // -> /user/eduardo
//path와 params는 함께 사용할 수 없다.
router.push({ path: '/user', params: { username } }) // -> /user

2. 현재 위치 변경

(= window.history.replace)

push와의 차이점은 히스토리 스택에 새로운 항목을 추가하지 않고 대체된다는 점이다.
선언적 방식

<router-link :to="..." replace>

프로그래밍 방식

router.replace(...)

아래와 같이 작성 가능

router.push({ path: '/home', replace: true })
// equivalent to
router.replace({ path: '/home' })

3. history 이동

(= window.history.go)

window.history.go(n)과 유사하게 히스토리 스택에서 앞,뒤로 이동할 단계를 매개변수로 입력하여 경로를 이동할 수 있다.

// 이전으로
router.go(1)
//뒤로가기
router.go(-1)

// 3 records 만큼 앞으로
router.go(3)

// 입력한 매개변수만큼의 레코드가 없을 경우 실패한다.
router.go(-100)
router.go(100)

위의 3가지 내비게이션 메소드 router.push, router.replace, router.gowindow.history.pushState, window.history.replaceState, window.history.go에 해당하며 window.history API를 모방한다고 한다.

하지만 Vue Router 내비게이션 메소드는 history 옵션의 종류와 상관없이 동일하게 작동한다.

참고 - Vue Router 공식 문서
https://next.router.vuejs.org/guide/

profile
🐋 https://ye-yo.github.io/ 로 블로그 이전했습니다

0개의 댓글