코알못

[Vue] 페이지 이동 구현 (Router) 본문

JAVASCRIPT

[Vue] 페이지 이동 구현 (Router)

코린이s 2022. 6. 12. 01:29
728x90

페이지 이동을 위한 라이브러리인 router 을 배워보자!

아래 명령어를 입력하여 vue-router 을 설치한다 (저자는 vue3 를 사용하며 해당 버전에 맞게 설정을 진행할 예정이다.)

// vue3
$ npm i vue-router@next
// vue2
$ npm install vue-router

src 하위에 router.js 를 생성한 뒤 아래와 같이 '/' 일시 Home.vue, 그외 URL 호출시 'ErrorPage.vue' 를 보여주도록 한다.

// router.js

import {createWebHistory, createRouter} from "vue-router";
import ErrorPage from "./views/ErrorPage";
import Home from "./views/Home";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home
    },
    {
        path: "/:catchAll(.*)",
        name: "ErrorPage",
        component: ErrorPage
    }
]
const router = createRouter({
    history: createWebHistory(),
    routes
})
export default router;

해당 라우터 설정을 main.js 에 등록한다.

import { createApp } from 'vue'
import App from './App.vue';
import router from "@/router";

const app = createApp(App);
app.use(router);
app.mount("#app");

다음으로 보여줄 Home, ErrorPage vue를 src/views 디렉토리 하위에 생성한다.

// Home.vue

<template>
    <div>
        <h1>Home Page</h1>
    </div>
</template>

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

<style>
</style>

 

// ErrorPage.vue

<template>
    <div>
        <h1>Error Page</h1>
    </div>
</template>

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

<style>
</style>

해당 뷰를 출력하기 위해서는 최상위 뷰에서 <router-view/> 를 작성하여 라우팅할 뷰를 보여줄 수 있도록 한다.

<template>
    <div>
        <router-view />
    </div>
</template>

<script>
    export default {
        name:"App"
    };
</script>

<style>
</style>

이제 실행 하도록 한다.

$npm run serve
 DONE  Compiled successfully in 1152ms                                                                   1:15:31 AM


  App running at:
  - Local:   http://localhost:8080/ 
  - Network: http://[IP]:8080/

기본 path인 '/' 로 접속시 정상적으로 Home vue 화면이 노출되고

그 외 페이지로 접속시 ErrorPage vue 가 노출된다.

# 오류 

1) Component name "파일명" should always be multi-word  vue/multi-word-component-names
- 원인 : Component 명을 단어의 조합으로 만들지 않아서 생기는 이슈
- 해결 : 단어의 조합으로 파일 이름을 생성하거나 단어의 조합으로 생성하지 않아도 되도록 설정
// vue.config.js
- lintOnSave : false 로 설정하며 설정후에 재기동 하여 적용 한다.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false
})
728x90
Comments