공부/Vue.js

[Vue.js] Vue Router 란? / vue router 예제

bumcrush 2019. 7. 18. 21:41
반응형

1. Vue Router 란?

  • 웹페이지 간의 이동 방법
  • 보통 브라우저에서 웹 페이지를 요청하면 서버에서 응답을 받아 다시 사용자에게 돌려주는 시간 동안 환면 상에 깜빡거리는 현상이 나타나는데, 이런 부분을 라우팅을 처리하면 화면을 깜빡임 없이 매끄럽게 전환할 수 있으면 , 더 빠르게 화면을 조작하여 사용자 경험이 향상된다.
  • 싱글 페이지 애플리케이션(SPA)에서 많이 사용

 

2. Vue Router 프로젝트 생성
- 적당한 폴더에 프로젝트 생성(cli를 통해서 만듦) 

> vue create vue-router-app

 

3. vue router 설치

- vs code로 프로젝트 열고 아래 명령어 입력

> npm install --save vue-router

 

4. vue router 예제 코드 생성
- 생략해도 무관 

> vue add router

vue router / vue.js / 뷰 라우터 / 라우터 /vue

5. Vue Router 프로젝트 구조 

vue router 프로젝트 구조

 


6. vue router 예제 코드

 

6-1.  src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

 

6-2. src/router.js

import Vue from 'vue'
import Router from 'vue-router'
import Posts from './views/Posts.vue'
import PostNew from './views/PostNew.vue'
import PostDetail from './views/PostDetail.vue'
import test from './views/test.vue'

Vue.use(Router)  //플러그인 등록

export default new Router({
  routes: [
    {
      path: '/posts',
      //name: 'home',
      component: Posts,
      children: [
        { path: 'new', component: PostNew},
        { path: ':id', name: 'post', component: PostDetail}  //PostDetail
        ]
    },
    {
      path: '/about', 
      //name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    },
    {
      path: '/test', 
      component: test
    }
  ]
})

 

6-3. src/App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/posts"> Posts</router-link> |
      <router-link to="/posts/new" exact>New Post</router-link> |
      <router-link to="/posts/detail" exact>Detail Post</router-link> |
      <router-link to="/test" >test</router-link> |
    </div>
    <router-view/>
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.router-link-active {
color: white;
background-color: red;
}
.router-link-exact-active {
color: white;
background-color: blue;
}
</style>

 

6-4. src/views/test.vue

<template>
    <div>
       <h3>test 페이지 입니다.</h3>
    </div>
</template>

<script>
//import { Post } from '../api/index'
export default {
    data() {
        return { loading: false, posts: [] }
    }
   
}
</script>


 

6-5. src/views/Post.vue

<template>
    <div>
        <h1>Posts</h1>
        <div v-if="loading">안녕하세요?포스트입니다.</div>
        <div v-for="post in posts" :key="post.id">
            <router-link :to="{ name: 'post', params: { id: post.id } }">
                [ID: {{post.id}}] {{post.text| summary}}
            </router-link>
        </div>
        <router-view></router-view>
    </div>
</template>

<script>
import { Post } from '../api/index'
export default {
    data() {
        return { loading: false, posts: [] }
    },
    created() { 
        this.fetchData() 
        },
    filters: {
        summary(val) {
           return val.substring(0, 20) + '...'
        }
    },
    methods: {
        fetchData() {
            this.loading= true
            Post.list()
            .then(data => {
                this.posts= data
                this.loading= false
        })
        }
    }
}
</script>


 

6-6. src/views/PostNew.vue

<template>
    <div>
        <h1>Post New page</h1>
        <h2>New Post</h2>
        <form @submit.prevent="onSubmit">
            <textarea cols="30" rows="10" v-model="inputTxt" :disabled="disabled"></textarea>
            <input type="submit" :value="btnTxt" :disabled="disabled"/>
        </form>
    </div>
</template>

<script>
import { Post } from '../api'
export default {
    data() {
        return { 
            isSaving: false, 
            inputTxt: '', 
            }
    },
    computed: {
        btnTxt() {
            return this.isSaving? 'Saving...' : 'Save'
            },
        disabled() { 
            return this.isSaving
            }
            },
    methods: {
        onSubmit() {
            this.isSaving= true
            Post.create(this.inputTxt).then(() => {
                this.isSaving= false 
                this.inputTxt= '테스트 좀 합니다'
                this.$router.push('/posts')
                })
        }
    }
}
</script>


 

6-7. src/views/PostDetail.vue

<template>
    <div>
      <h1>Post Detail page</h1>
      <h1>This is an id: {{this.$route.params.id}} <br></h1>






    </div>
</template>

<script>
import { Post } from '../api'
export default {
    data() {
            return {
            post: null,
            loading: true
            }
        },
    created() {
        this.fetchData() 
        },
    watch: { 
        '$route': 'fetchData' 
        },
    methods: {
        fetchData() {
            this.post= null
            this.loading= true
            Post.get(this.$route.params.id)
            .then(data => { 
                this.post= data
                this.loading= false
                })
        }
    }
}
</script>

 

6-8. src/views/About.vue

<template>
  <div class="about">
    <div>
      <router-link to="/">Home</router-link>|
      <router-link to="/posts">posts</router-link>
    </div>
  <router-view/>
  </div>
</template>

 

7. 실행 및 실행화면

>npm run serve

 

posts 눌렀을때

 

new posts

* 참고로 posts 밑에 newPosts가 자식컴포넌트로 들어가 있는 형태다.

연습할 때 막 만든 코드라 솔직히 정리 안되고 지저분하다 ㅠ

 

 

8. 코드 전문

https://github.com/sbomhoo/vue-router-test

 

sbomhoo/vue-router-test

Vue-Router 예제. Contribute to sbomhoo/vue-router-test development by creating an account on GitHub.

github.com

 

반응형
  • 현재글[Vue.js] Vue Router 란? / vue router 예제