Study/Vue3

[Vue3] 페이지 이동 함수 - router

hyjang 2025. 3. 10. 12:20
728x90

 

router로 페이지를 이동하는 함수에는 세가지가 있다.

· push  : URL 이동. 히스토리 스택에 추가된다.
· replace  : URL 이동. 현재 페이지를 대체하므로 히스토리 스택에 추가되지 않는다.
· go  : 히스토리 이동. 숫자만큼 앞, 뒤로 이동할 수 있다.

 

$router.push

this.$router.push('/') // URL로 이동
this.$router.push({name: 'home'})  // /home 으로 이동
this.$router.push({name: 'detail', params: {id: '001'} })  // /detail/001 로 이동
this.$router.push({ path:'/list', query: { tag: 'vue' } }); // list?tag=vue 로 이동

- 동적 경로(/detail/:id)로 데이터를 전달할 때 -> params 사용

- 검색 필터, 정렬같은 데이터를 전달할 때 -> query 사용

 

$router.replace

this.$router.push('/step1');  // step1으로 이동 (히스토리 추가)
this.$router.push('/step2');  // step2로 이동 (히스토리 추가)
this.$router.replace('/final');  // 최종적으로 final로 이동 (step2는 히스토리에서 삭제됨)

- 뒤로 가기를 하면 step1로 이동한다.

$router.go(n)

this.$router.go(1)   // 앞으로 1페이지 이동 ( forward() )
this.$router.go(-1)  // 뒤로 1페이지 이동 ( back() ) 
this.$router.go(3)   // 앞으로 3페이지 이동
this.$router.go(0)   // 현재 페이지 새로고침
this.$router.go(100) // 100만큼의 기록이 없으면 반응이 없다.

Composition API - useRouter

Composition API를 사용할 때는 this가 Vue 인스턴스를 참조하지 않기 때문에 타입 오류가 있을 수 있다.

따라서 Composition API에서는 useRouter를 사용한다.

<script setup lang="ts">
import { useRouter } from 'vue-router';

const router = useRouter();

const goHome = () => {
 router.push('/');
 };
</script>

<template>
  <button @click="goHome">홈으로 이동</button>
</template>