목차
Router
Route / Router
- Route
- 라우트(경로)는 URL과 그 URL이 표시해야 할 컨텐츠 사이의 매핑이다. 즉, 웹 애플리케이션에서 사용자가 접근할 수 있는 개별 경로나 페이지를 지정한다.
- 예를 들어, /about URL에 접속하면 "About Us" 페이지를, /contact URL에 접속하면 "Contact Us" 페이지를 보여주는 것을 말한다.
- Router
- 라우터는 라우트들의 모음이며, 다양한 라우트들을 관리하고 조정하는 역할을 한다.
- 애플리케이션에서 발생하는 URL의 변화를 감지하고, 해당 URL에 매핑된 라우트를 찾아 그에 맞는 컨텐츠를 렌더링한다.
Vue Router
Vue Router | The official Router for Vue.js
The official Router for Vue.js
router.vuejs.org
- SPA에서는 사용자가 다른 페이지로 이동할 때마다 서버에 요청을 보내고 새 페이지를 불러오는 대신, 클라이언트 사이드에서 페이지를 동적으로 렌더링한다.
- SPA는 하나의 HTML 파일만 사용하기 때문에 기본적으로 하나의 URL만 가질 수 있다.
- 하나의 HTML 파일만 사용하지만 AJAX를 통해 페이지를 동적으로 렌더링이 가능하여 사용자는 여러 페이지에 접속하는 것처럼 사용할 수 있다.
- 하지만, 사용자는 URL의 변화를 감지할 수 없을 뿐더러 URL을 통해 웹사이트를 공유하면 공유받은 사람은 웹사이트의 홈페이지만 확인할 수 있다.
Vue Router를 사용하면 SPA의 장점과 더불어 URL의 변화도 감지할 수 있다.
실습
- vue 프로젝트를 생성
- vue@latest는 pinia, vue-router가 포함된 scaffold이다.
$ npm create vue@latest .
- 옵션 선택
- Add Vue Router, Add Pinia만 Yes 선택
√ Project name: ... vue-project
√ Add TypeScript? ... No / Yes
√ Add JSX Support? ... No / Yes
√ Add Vue Router for Single Page Application development? ... No / Yes
√ Add Pinia for state management? ... No / Yes
√ Add Vitest for Unit Testing? ... No / Yes
√ Add an End-to-End Testing Solution? » No
√ Add ESLint for code quality? ... No / Yes
√ Add Vue DevTools 7 extension for debugging? (experimental) ... No / Yes
- 모듈 설치
$ npm install
$ npm i sass
- 서버 실행
$ npm run dev
- 홈페이지 /
- about 페이지 /about
router 사용법
views vs components
- src안에 기존에 존재하던 components 외에 views가 생성이 된다.
- views는 다른 페이지로 이동을 할 때 변경되는 화면에 대한 컴포넌트이다.
- 부모 컴포넌트의 <RouterView /> 요소의 위치에 렌더링된다.
router
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
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('../views/AboutView.vue')
}
]
})
export default router
- routes
- url과 url을 통해 보여줄 화면을 연결한다.
- path : url을 설정한다.
- component : views에 작성된 url을 통해 보여줄 컴포넌트를 설정한다.
- name : path ↔ component 연결에 대한 이름이며, 해당 route에 대한 변수명이다.
RouterLink
- vue router에서 사용하는 특수한 a태그이며, routes에 정의된 path와 연결된 view를 <RouterView />에 렌더링한다.
- / : 홈페이지, /about : about페이지, /my : my페이지 세종류의 페이지를 만들어보자
- MyView.vue 생성
- src/views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
</div>
</template>
<script setup>
</script>
<style lang="scss" scoped>
</style>
- routes 정의
- src/router/index.js
- 보여줄 view를 import
- path, component 연결
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import MyView from '../views/MyView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
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('../views/AboutView.vue')
},
{
path: '/my',
name: 'my',
component: MyView
},
]
})
export default router
- App.vue에 RouterLink 생성
- App.vue
- path에 작성한 /my뿐 아니라 name에 작성한 변수명으로도 route를 지정할 수 있다.
- 이때 : 속성 바인딩을 활용한다.
- path에 작성한 /my뿐 아니라 name에 작성한 변수명으로도 route를 지정할 수 있다.
- App.vue
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink :to="{name : 'my'}">My</RouterLink>
</nav>
프로그래밍 방식 네비게이션
- RouterLink를 사용하는 방식이 아닌, JavaScript 코드를 활용하여 다른 페이지로 이동할 수 있다.
- vue-router에서 제공하는 router의 메서드인 router.push()를 사용하여 다른 페이지로 이동할 수 있다.
- views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
<button @click="goHome">홈으로</button>
<button @click="goAbout">어바웃으로</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function goHome() {
router.push('/')
}
function goAbout() {
router.push('/about')
}
</script>
<style lang="scss" scoped>
</style>
Dynamic Route Matching
- URL의 일부를 변수로서 활용할 수 있다.
- django의 path('articles/<int:id>/)에서 id를 활용하는 것과 같은 기능
- routes 정의
- path에 변수로 사용할 부분은 :변수이름으로 작성한다.
import NumberView from '../views/NumberView.vue'
const router = createRouter({
routes: [
...,
{
path: '/number/:num',
name: 'number',
component: NumberView
},
]
})
export default router
- NumberView.vue 생성
- src/views/NumberView.vue
- vue-router에서 제공하는 route에서 params에 Dynamic Route Matching에 대한 변수가 들어있다.
- routes의 path에 :num으로 작성했으므로, route.params.num로 해당 값에 접근할 수 있다.
- src/views/NumberView.vue
<template>
<div>
<h1>
{{ num }}
</h1>
</div>
</template>
<script setup>
import {useRoute} from 'vue-router'
const route = useRoute()
const num = route.params.num
</script>
[실습]
- /contact를 통해 접근할 수 있는 ContactView를 구현하자.
- 프로그래밍 방식 네비게이션을 활용하여 MyView에서 ContactView로 이동하는 기능을 구현하자.
- src/views/ContactView.vue
<template>
<div>
<h1>Contact Us</h1>
<p>Contact information goes here...</p>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import MyView from '../views/MyView.vue'
import ContactView from '../views/ContactView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
},
{
path: '/my',
name: 'my',
component: MyView
},
{
path: '/contact',
name: 'contact',
component: ContactView
}
]
})
export default router
- src/views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
<button @click="goToContact">Go to Contact</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function goToContact() {
router.push({ name: 'contact' }) // 네임으로 라우팅
}
</script>
<style scoped>
</style>
'Vue' 카테고리의 다른 글
Vue(Backend) : Django(Frontend) (0) | 2024.03.28 |
---|---|
Pinia (0) | 2024.03.27 |
Vue 실습(2) (0) | 2024.03.27 |
Vue : Component, Props, Emit (0) | 2024.03.27 |
Vue 실습(1) (0) | 2024.03.27 |
Router
Route / Router
- Route
- 라우트(경로)는 URL과 그 URL이 표시해야 할 컨텐츠 사이의 매핑이다. 즉, 웹 애플리케이션에서 사용자가 접근할 수 있는 개별 경로나 페이지를 지정한다.
- 예를 들어, /about URL에 접속하면 "About Us" 페이지를, /contact URL에 접속하면 "Contact Us" 페이지를 보여주는 것을 말한다.
- Router
- 라우터는 라우트들의 모음이며, 다양한 라우트들을 관리하고 조정하는 역할을 한다.
- 애플리케이션에서 발생하는 URL의 변화를 감지하고, 해당 URL에 매핑된 라우트를 찾아 그에 맞는 컨텐츠를 렌더링한다.
Vue Router
Vue Router | The official Router for Vue.js
The official Router for Vue.js
router.vuejs.org
- SPA에서는 사용자가 다른 페이지로 이동할 때마다 서버에 요청을 보내고 새 페이지를 불러오는 대신, 클라이언트 사이드에서 페이지를 동적으로 렌더링한다.
- SPA는 하나의 HTML 파일만 사용하기 때문에 기본적으로 하나의 URL만 가질 수 있다.
- 하나의 HTML 파일만 사용하지만 AJAX를 통해 페이지를 동적으로 렌더링이 가능하여 사용자는 여러 페이지에 접속하는 것처럼 사용할 수 있다.
- 하지만, 사용자는 URL의 변화를 감지할 수 없을 뿐더러 URL을 통해 웹사이트를 공유하면 공유받은 사람은 웹사이트의 홈페이지만 확인할 수 있다.
Vue Router를 사용하면 SPA의 장점과 더불어 URL의 변화도 감지할 수 있다.
실습
- vue 프로젝트를 생성
- vue@latest는 pinia, vue-router가 포함된 scaffold이다.
$ npm create vue@latest .
- 옵션 선택
- Add Vue Router, Add Pinia만 Yes 선택
√ Project name: ... vue-project
√ Add TypeScript? ... No / Yes
√ Add JSX Support? ... No / Yes
√ Add Vue Router for Single Page Application development? ... No / Yes
√ Add Pinia for state management? ... No / Yes
√ Add Vitest for Unit Testing? ... No / Yes
√ Add an End-to-End Testing Solution? » No
√ Add ESLint for code quality? ... No / Yes
√ Add Vue DevTools 7 extension for debugging? (experimental) ... No / Yes
- 모듈 설치
$ npm install
$ npm i sass
- 서버 실행
$ npm run dev
- 홈페이지 /
- about 페이지 /about
router 사용법
views vs components
- src안에 기존에 존재하던 components 외에 views가 생성이 된다.
- views는 다른 페이지로 이동을 할 때 변경되는 화면에 대한 컴포넌트이다.
- 부모 컴포넌트의 <RouterView /> 요소의 위치에 렌더링된다.
router
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
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('../views/AboutView.vue')
}
]
})
export default router
- routes
- url과 url을 통해 보여줄 화면을 연결한다.
- path : url을 설정한다.
- component : views에 작성된 url을 통해 보여줄 컴포넌트를 설정한다.
- name : path ↔ component 연결에 대한 이름이며, 해당 route에 대한 변수명이다.
RouterLink
- vue router에서 사용하는 특수한 a태그이며, routes에 정의된 path와 연결된 view를 <RouterView />에 렌더링한다.
- / : 홈페이지, /about : about페이지, /my : my페이지 세종류의 페이지를 만들어보자
- MyView.vue 생성
- src/views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
</div>
</template>
<script setup>
</script>
<style lang="scss" scoped>
</style>
- routes 정의
- src/router/index.js
- 보여줄 view를 import
- path, component 연결
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import MyView from '../views/MyView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
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('../views/AboutView.vue')
},
{
path: '/my',
name: 'my',
component: MyView
},
]
})
export default router
- App.vue에 RouterLink 생성
- App.vue
- path에 작성한 /my뿐 아니라 name에 작성한 변수명으로도 route를 지정할 수 있다.
- 이때 : 속성 바인딩을 활용한다.
- path에 작성한 /my뿐 아니라 name에 작성한 변수명으로도 route를 지정할 수 있다.
- App.vue
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink :to="{name : 'my'}">My</RouterLink>
</nav>
프로그래밍 방식 네비게이션
- RouterLink를 사용하는 방식이 아닌, JavaScript 코드를 활용하여 다른 페이지로 이동할 수 있다.
- vue-router에서 제공하는 router의 메서드인 router.push()를 사용하여 다른 페이지로 이동할 수 있다.
- views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
<button @click="goHome">홈으로</button>
<button @click="goAbout">어바웃으로</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function goHome() {
router.push('/')
}
function goAbout() {
router.push('/about')
}
</script>
<style lang="scss" scoped>
</style>
Dynamic Route Matching
- URL의 일부를 변수로서 활용할 수 있다.
- django의 path('articles/<int:id>/)에서 id를 활용하는 것과 같은 기능
- routes 정의
- path에 변수로 사용할 부분은 :변수이름으로 작성한다.
import NumberView from '../views/NumberView.vue'
const router = createRouter({
routes: [
...,
{
path: '/number/:num',
name: 'number',
component: NumberView
},
]
})
export default router
- NumberView.vue 생성
- src/views/NumberView.vue
- vue-router에서 제공하는 route에서 params에 Dynamic Route Matching에 대한 변수가 들어있다.
- routes의 path에 :num으로 작성했으므로, route.params.num로 해당 값에 접근할 수 있다.
- src/views/NumberView.vue
<template>
<div>
<h1>
{{ num }}
</h1>
</div>
</template>
<script setup>
import {useRoute} from 'vue-router'
const route = useRoute()
const num = route.params.num
</script>
[실습]
- /contact를 통해 접근할 수 있는 ContactView를 구현하자.
- 프로그래밍 방식 네비게이션을 활용하여 MyView에서 ContactView로 이동하는 기능을 구현하자.
- src/views/ContactView.vue
<template>
<div>
<h1>Contact Us</h1>
<p>Contact information goes here...</p>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
- src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import MyView from '../views/MyView.vue'
import ContactView from '../views/ContactView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: AboutView
},
{
path: '/my',
name: 'my',
component: MyView
},
{
path: '/contact',
name: 'contact',
component: ContactView
}
]
})
export default router
- src/views/MyView.vue
<template>
<div>
<h1>This is My View</h1>
<button @click="goToContact">Go to Contact</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
function goToContact() {
router.push({ name: 'contact' }) // 네임으로 라우팅
}
</script>
<style scoped>
</style>
'Vue' 카테고리의 다른 글
Vue(Backend) : Django(Frontend) (0) | 2024.03.28 |
---|---|
Pinia (0) | 2024.03.27 |
Vue 실습(2) (0) | 2024.03.27 |
Vue : Component, Props, Emit (0) | 2024.03.27 |
Vue 실습(1) (0) | 2024.03.27 |