Vue.js_Router

보현·2020년 7월 14일
1

VueJs

목록 보기
9/14

Vue프로젝트를 처음 생성했을 때의 기본 폴더구조이다.
프로젝트 생성할때 플러그인 설치에 라우터를 포함시켜야 기본생성된다.

페이지렌더링되는 순서

1.index.html : 싱글페이지
2.main.js : vue 인스턴스 생성
3.App.vue :
4.index.js : 라우터
5.component(Home,About) : 실제데이터 컴포넌트

1. public > index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Vue는 SPA(Single Page Application)로서, 로딩을 다시하지않고 이 페이지안에서 모든게 이루어진다.
#app 에서 페이지가 이루어진다

2. src > main.js

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

Vue.config.productionTip = false

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

main.js에서는 vue 인스턴스가 생성되며 index.html의 #app과 연결된다.
또한 render함수에서 App.vue를 맨처음 보여주게끔 연결한다.

3. src > App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

<style>
//css
</style>

router-link 가 a태그 같은역할을하고, 클릭하면 to속성값 뒤에 path로 컴포넌트가 연결된다.
path는 라우터에서 정의한다.

Home 버튼을 누르면 아래 router-view태그에서 해당컴포넌트로 바꿔치기!!!

4. router > index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [{
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/about',
        name: 'About',
        component: () =>
            import ('../views/About.vue')
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

라우터에는 path(url 주소), name, 연결되는 component 이 세가지 속성으로 구성된다.
App.vue 파일에서 path가 "/"으로 연결이되면 Home컴포넌트가 열리고,
path가 "/about"으로 연결이되면 About컴포넌트가 열린다.

라우터에서 컴포넌트 연결방법

  1. Home 컴포넌트 연결방식처럼 위에서 컴포넌트의 파일경로를 import해주고 routes오브젝트에서 컴포넌트 이름으로만 연결한다.
  2. About 컴포넌트 연결방식처럼 import하지않고 routes오브젝트 안에서 바로 파일경로를 연결한다.

5. Home.vue (컴포넌트)

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  }
}
</script>

드디어 라우터로 연결된 컴포넌트 페이지가 열리게된다.
페이지가 바뀌며 열리는것처럼 보이지만 사실상 모든 것은 index.html 한페이지에서 진행된다.

profile
실천하는 보현이가 되자, 제발

0개의 댓글