[Vue] Router

에구마·2023년 11월 28일
0

Vue

목록 보기
5/6

Vue Router

뷰에서 라우팅을 하는 데에 두가지 모드가 있다.

  • 해시모드 createWebHashHistory
    도메인/#/~

    • 장점 : 기본 도메인으로만 한번 요청하고, 그 이하는 요청을 서버로 전송하지 않고 #를 통해 하나의 페이지에서 구분하는 방식임. 서버 요청 필요 없음.
    • 단점 : 주소에 #.. 하나의 도메인이기에 검색엔진최적화 등에 문제
  • **HTML5모드 (History 모드) createWebHistory
    도메인/~

    • 장점 : 주소 깔끔. 검색엔진 최적화 등에 좋음 권장
    • 단점 : 주소에 맞게 매번 서버에 요청해야함. SPA를 고려한다면, 서버에 나머지 페이지들을 처리할 필요없이 index.html 에 동작하도록 세팅해야함. 그래도 서버에 기본 구성 필요함


해시모드

npm install vue-router@4

기본 세팅

//main.js

import { createApp } from "vue";
import App from "./App";
import router from "~/routes"; // routes/폴더의 index.js를 가져와 router로 제어한다는 의미! index.js에서 export default한 것들을 쓸 수 있게 되는 것이다

const app = createApp(App);
app.use(router); // 플러그인으로 등록했기 때문에 $router로 접근이 가능해진다.
app.mount("#app");
import { createRouter, **createWebHashHistory** } from "vue-router";
import Home from "./Home";
import About from "./About";
import NotFound from "./NotFound";

export default createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      component: Home,
    },
    {
      path: "/about",
      component: About,
    },
    {
      path: "/:notFound(.*)",
      component: NotFound,
    },
  ],
});
  • main.js에서 router로 받아 사용할 인스턴스를 생성하여 export default 한다.
  • history 옵션
  • routes 옵션 : 경로와 컴포넌트를 객체로 가지는 배열로 선언한다.

RouterLink와 RouterView

최상위인 App.vue 컴포넌트에서 경로에 따라 다른 컴포넌트를 부르기 위해선 두가지 컴포넌트태그를 사용할 수 있다.

// App.vue
<template>
  <RouterLink to="/">Home</RouterLink>
  <RouterLink to="/about">About</RouterLink>
  <RouterView />
  <div>이건 App.vue</div>
</template>

<script>
export default {};
</script>
  • < RouterLink to =”경로”>
  • < RouterView /> 이 태그의 영역에, 경로에 따른 컴포넌트의 출력화면이 위치한다.

$router 와 $route

페이지 이동을 위해 위의 < RouterLink > 외에 $router.push를 이용할 수 있다.

$router에는 페이지를 조작할 수 있는 .push 등의 메소드가 있다.

<template>
  <!-- <RouterLink to="/">Home</RouterLink>-->
  <!--<RouterLink to="/about">About</RouterLink> -->
  <button @click="$router.push('/')">Home</button>
  <button @click="$router.push('/about')">About</button>
  <RouterView />
  <div>이건 App.vue</div>
</template>

<script>
export default {};
</script>

또한, 컴포넌트에서 접근할 수 있는 $route 가 있다.
각 컴포넌트에 대해 this.$route 객체는 현재 페이지에 대한 정보를 가진다!

query는 ?로 시작하고 &로 구분한다
params는 :로 시작한다.

param에 동적 파라미터사용

index.js에서 경로 지정시 : 를 사용하여 동적 파라미터를 둘 수도 있다.

컴포넌트에선 $route.params.파라미터명 으로 접근할 수 있다.

파라미터를 사용하여 특정 하위 컴포넌트를 보여주는 두가지 방법이 있다.

  1. childrend 옵션사용

    {
        path: "/documents",
        component: Docs,
        **children**:[
          {
            path: ":id",
            component: DocsId,
          },
        ]
      },

    이때, 상위 컴포넌트에서 하위 경로에 대한 컴포넌트를 보여줄 영역을 지정해줘야한다!! < RouterView />를 사용한다.

    <template>
      <h1>Docs.vue</h1>
      **<RouterView /> // <<-- 여기에 하위 컴포넌트 내용이 출력됨!**
    </template>
    <script>
    export default {};
    </script>

    단, 화면에 상위,하위 내용 모두 출력된다.

  2. 경로를 개별적으로 각각 지정한다.

    해당되는 경로의 컴포넌트 하나만 출력된다.

    {
      path: "/documents", 
      component: Docs,
    },
    {
      path: "/documents/:id", 
      component: DocsId,
    },

routes의 name 속성

routes의 각 객체에 name 속성이 있다.

{
  path: "/home", 
  component: Home,
	**name : home // <-name 지정!**
},

이 name을 라우터 이동에 경로대신 사용할 수 있다!

<button @click="$router.push('/')">Home</button>
대신
<button @click="$router.push(**{ name : 'home' }** )">Home</button>

RouterLink에서도 가능하다

<RouterLink to="/about:id=12?name=leon&age=83">Home</RouterLink>
대신

<RouterLink :to="{
	name : 'docsId',
	params: { id : '12' },
	query : {name: 'leon', age : 83}
}">DocsId</RouterLink>


HTML5모드 (History 모드)

//index.js

import { createRouter, **createWebHistory** } from "vue-router";
import About from "./About";

export default createRouter({
  history: **createWebHistory**(),
  routes: [
    {
      path: "/about",
      component: About,
    },
  ],
});

HTML5모드는 index.html를 기준으로 하기 때문에, 특정 경로로 이동한 상태에서 새로고침 등이 발생되면 페이지를 찾지 못한다. 그래서 webpack.config.js에 아래와 같은 설정이 필요하다.

module.exports = {
  ...
  output: {
    ...
    **publicPath: "/", /// 기준index.html로부터 절대경로로 /main.js를 찾도록 한다.**
  },
  ...
  devServer: {
    **historyApiFallback: true, /// 특정경로로 요청왔을때 기본 index.html로 리다이렉트시키고 그 이후에 해당 페이지를 보여주는 작업이 일어난다.**
  },
};
profile
코딩하는 고구마 🍠 Life begins at the end of your comfort zone

0개의 댓글

관련 채용 정보