• 여러 페이지를 만들려면 라우터를 사용을 해줘야하는데 설치가 필요하다
  • npm install vue-router@4 : 이 코드를 통해 라우터 설치가 가능하다.
    • 혹시 에러가 난다면 npm run serve해서 켜놨던 서버를 종료하고 재설치를 해보거나 yarn add를 쓰는것도 좋은 방법이다
  • src폴더 내에 router.js파일을 생성해 준다.
    • import { createWebHistory, createRouter } from "vue-router";
      
      const routes = [
        {
          path: "uri경로",
          component: import해온 컴포넌트,
        }
      ];
      
      const router = createRouter({
        history: createWebHistory(),
        routes,
      });
      
      export default router;
    • 위의 코드를 router.js에 입력해주고 앞으로 만들 페이지들중 라우터에 등록하고 싶은 페이지가 있다면 router.js에 import 해 온후 path와 컴포넌트를 등록해준다.
      • path : www.sitename.com/이곳에 오는 값이 uri // uri의 값을 정하고 해당 uri가 입력되면 해당 컴포넌트를 보여주겠다는 의미이다.
  • main.js에 라우터를 import해준다.
    • import router from './router'
      createApp(App).use(router).mount('#app')
  • App.vue혹은 자신이 원하는 컴포넌트 파일 내에서 라우터를 사용하겠다는 태그를 입력해 준다.
    • <template>
      	<h1>My Page</h1>
      	<router-view></router-view>
      </template>
    • <router-view>를 사용한 부분에 라우터로 가져온 페이지를 보여줍니다.
  • 페이지 이동 경로 설정 방법
    • <template>
      	<router-link to="/write">글 작성</router-link>
          <a href="/write">글 작성</a>
      </template>
    • 두가지 태그 모두 동일하게 동작합니다.

'Front-end > Vue.js' 카테고리의 다른 글

7. vue router - 3  (0) 2021.11.04
6. vue router - 2  (0) 2021.11.04
4. 라이프사이클(Life Cycle)  (0) 2021.11.03
3. Transition(Animation)  (0) 2021.11.03
2. 기초  (0) 2021.11.03

+ Recent posts