단순 코드 기록/Vue

Vue_Router 사용

일일일코_장민기 2024. 3. 12. 11:06
728x90

 

라우터란??
라우터란 한 마디로 '연결 장치'이다.
server.js 한 파일에서만 런칭하는 것이 아니라
router를 이용하여 여러 .js 파일에 원하는 코드를 짤 수 있다는 것이다.

router를 이용하는 이유는 코드의 간략화 + 가독성 때문이다.
server.js 하나에 넣으면 길이도 길어지고 가독성이 떨어진다.
수정하기도 힘들어진다.
이런 문제를 해결하기 위해 router를 쓰면 편리하게 코딩을 할 수 있다.

 

App.vue
<template>
  <div>
    <h1> App에서 라우팅 연습 </h1>
    <router-link to="/">Home</router-link><br>
    <router-link to="/login">login</router-link><br>

    <!-- 링크 컴포넌트가 보여질 부분 -->
    <router-view></router-view><br>

  </div>
</template>

<script>
//컴포넌트 import가 없음
//모든 라우팅 주소는 router 설치 후
//라우터 설치할 곳> npm install vue-router@3
//router.js 생성 후 주소를 router.js파일에 등록함
//router를 main.js에 최종등록
export default {
    components:{
      //없음
    },
}
</script>
<style>
</style>

 

Bar.vue

 

<template>
  <div>
    <h1>{{ mesg }}</h1>
    <h1>bar2</h1>
  </div>
</template>

<script>
export default {

    props:{
        mesg:String
    }

}
</script>

<style>

</style>
Foo.vue
<template>
    <div>
      <h1>{{ mesg }}</h1>
      <h1>foo2</h1>
    </div>
  </template>
 
  <script>
  export default {
 
      props:{
          mesg:String
      }
 
  }
  </script>
 
  <style>
 
  </style>

 

NotFound.vue
<template>
    <div>
      <h1>{{ mesg }}</h1>
      <h1>not found!</h1>
    </div>
  </template>
 
  <script>
  export default {
 
      props:{
          mesg:String
      }
 
  }
  </script>
 
  <style>
 
  </style>

 

router.js
//Import
import Vue from "vue";
import VueRouter from "vue-router";

//컴포넌트 자식창
import Bar from './components/Bar.vue';
import Foo from './components/Foo.vue';
import NotFound from './components/NotFound.vue';

//경로 설정
const routes = [
    //배열로 주소 등록
    { path: "/", component: Bar, name: "Bar"},
    { path: "/login", component: Foo, name: "Foo"},
    { path: "/**", component: NotFound, name: "NotFound"},      //if~else 개념: 위에 작성하면 모든 경로가 NotFound로 연결
];

//실제 사용할 라우터 export
//VueRouter를 주소 등록 후 생성
const router = new VueRouter({ routes });  
//VueRouter 사용 등록
Vue.use(VueRouter);
//main.js에서 라우터를 컴포넌트로 등록******************main.js로 이동
//실제 사용할 라우터 export
export default router;

 

main.js

 

import Vue from 'vue'
import App from './App.vue'
import router from "./router";        //*******추가(라우터 import)*******

Vue.config.productionTip = false

new Vue({
  router,                             //*******추가(라우터 등록)*******
  render: h => h(App),
}).$mount('#app')

 

 

 

'단순 코드 기록 > Vue' 카테고리의 다른 글

Vue_router_query로 데이터 전송  (0) 2024.03.12
Vue_Router_path별로 데이터 넘기기  (0) 2024.03.12
Vue_Spring 연결 + 형제 전송(eventBus)  (0) 2024.03.11
Vue_Spring과 연결  (0) 2024.03.11
Vue_slot_속성 활용  (0) 2024.03.11