vue-router

Leutbing·2023년 8월 22일
0

vue-router

페이지를 여러개 만들고 싶을 때 라우터를 사용한다.

1. 설치

npm install vue-router@4

2. 라우터파일 생성

import { createWebHistory, createRouter } from "vue-router";

const routes = [
  {
    path: "/경로",
    component: import해온 컴포넌트,
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router; 

3. main.js 라우터 등록

import router from './router'
createApp(App).use(router).mount('#app') 

4. 설정한 라우터로 구분된 페이지에 자리 설정

ex) App.vue의 HTML 내부 아무 곳에나 태그를 추가하면 라우터로 구분된 페이지를 그 자리에 보여준다.

<router-view></router-view>

5. 페이지 이동 링크 설정

to=""안에 마음대로 경로 설정이 가능하다.

<router-link to="/list">이동하기</router-link>

6. 동적 라우터 설정

router.js

const routes = [
	{
    	path : '/detail/:id,
        component : Detail,
    }
]

/detail/ 뒤에 아무거나 작성했을 때 항상 Detail.vue를 보여주라는 말이다.
:콜론기호를 붙이고 뒤에 아무거나 작성해주면 된다.

7. 동적 라우터에서 설정한 :뒤에 있는 URL에 가져오기

{{ $route.params.파라미터명 }}

8. nested routes

특정 페이지 내에서 라우트를 나누는 경우를 nested routes라고 한다.

const routes = [
  {
    path : '/fruit/:id',
    component : Fruit,
    children : [
      { path : 'banana', component : Banana},
      { path : 'apple', component : Apple },
    ]
  }
]

Fruit.vue에 <router-view></route-view>라는 태그를 추가하면 /fruit/:id/banana로 접속했을 때 <router-view>자리에 Banana 컴포넌트가 보인다.

9. 페이지 이동 링크 설정2

$router.push('/경로')

설정한 경로로 이동한다.

$router.go(-1)

뒤로가기 기능을 실행할 수 있다.
1라고 작성하면 앞으로 실행 할 수 있다.

$router 변수를 잘 사용하면 브라우저 방문기록을 들춰보거나 마음대로 조작할 수 있다.

profile
다시 개발을 도전하고 있습니다!! 🧑🏻‍💻

0개의 댓글