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>
'Study > Vue3' 카테고리의 다른 글
[Vue3] URL 쿼리스트링으로 검색 필터링하기 (0) | 2025.03.12 |
---|---|
[Vue3] input type="date" 임의로 날짜 입력하기 차단 (선택만 가능) (0) | 2025.03.07 |
[Vue3] vee-validate 간단한 사용법 (라이브러리로 유효성 검사하기) (0) | 2024.12.11 |
[Vue3] 자식컴포넌트 input value값 가져오기 (defineModel) (0) | 2024.12.10 |
[Vue3] watch 함수를 이용해서 url 쿼리스트링 값 실시간으로 가져오기 (0) | 2024.12.06 |