::: tip ์ฐธ๊ณ ์ด ๊ฐ์ด๋๋ ์ฝ๋์ํ์ ES2015๋ฅผ ์ฌ์ฉํฉ๋๋ค.
๋ํ ๋ชจ๋ ์์ ๋ Vue ์ ์ ๋ฒ์ ์ ์ด์ฉํด ๋ฐ๋ก ์ปดํ์ผ ํ ์ ์์ต๋๋ค. ๋ ์์ธํ ๋ด์ฉ์ ์ฌ๊ธฐ๋ฅผ ํ์ธํ์ธ์. :::
Vue์ Vue ๋ผ์ฐํฐ๋ฅผ ์ด์ฉํด ์ฑ๊ธ ํ์ด์ง ์ฑ์ ๋ง๋๋ ๊ฒ์ ๋งค์ฐ ์ฝ์ต๋๋ค. Vue.js๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ์ด๋ฏธ ์ปดํฌ๋ํธ๋ก ์ฑ์ ๊ตฌ์ฑํ๊ณ ์์ ๊ฒ์ ๋๋ค. Vue ๋ผ์ฐํฐ๋ฅผ ํจ๊ป ์ฌ์ฉํ ๋ ์ถ๊ฐ๋ก ํด์ผํ๋ ๊ฒ์ ๋ผ์ฐํธ์ ์ปดํฌ๋ํธ๋ฅผ ๋งคํํ ํ, ์ด๋ค ์ฃผ์์์ ๋ ๋๋งํ ์ง ์๋ ค์ฃผ๋ ๊ฒ ๋ฟ์ ๋๋ค.
์๋๋ ๊ธฐ๋ณธ ์์ ์ ๋๋ค.
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- ๋ค๋น๊ฒ์ด์
์ ์ํด router-link ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํฉ๋๋ค. -->
<!-- ๊ตฌ์ฒด์ ์ธ ์์ฑ์ `to` prop์ ์ด์ฉํฉ๋๋ค. -->
<!-- ๊ธฐ๋ณธ์ ์ผ๋ก `<router-link>`๋ `<a>` ํ๊ทธ๋ก ๋ ๋๋ง๋ฉ๋๋ค.-->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- ๋ผ์ฐํธ ์์ธ๋ -->
<!-- ํ์ฌ ๋ผ์ฐํธ์ ๋ง๋ ์ปดํฌ๋ํธ๊ฐ ๋ ๋๋ง๋ฉ๋๋ค. -->
<router-view></router-view>
</div>
// 0. ๋ชจ๋ ์์คํ
(์: vue-cli)์ ์ด์ฉํ๊ณ ์๋ค๋ฉด, Vue์ Vue ๋ผ์ฐํฐ๋ฅผ import ํ์ธ์
// ๊ทธ๋ฆฌ๊ณ `Vue.use(VueRouter)`๋ฅผ ํธ์ถํ์ธ์
// 1. ๋ผ์ฐํธ ์ปดํฌ๋ํธ๋ฅผ ์ ์ํ์ธ์.
// ์๋ ๋ด์ฉ๋ค์ ๋ค๋ฅธ ํ์ผ๋ก๋ถํฐ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. ๋ผ์ฐํธ๋ฅผ ์ ์ํ์ธ์.
// Each route should map to a component. The "component" can
// ๊ฐ ๋ผ์ฐํธ๋ ๋ฐ๋์ ์ปดํฌ๋ํธ์ ๋งคํ๋์ด์ผ ํฉ๋๋ค.
// "component"๋ `Vue.extend()`๋ฅผ ํตํด ๋ง๋ค์ด์ง
// ์ค์ ์ปดํฌ๋ํธ ์์ฑ์์ด๊ฑฐ๋ ์ปดํฌ๋ํธ ์ต์
๊ฐ์ฒด์
๋๋ค.
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. `routes` ์ต์
๊ณผ ํจ๊ป router ์ธ์คํด์ค๋ฅผ ๋ง๋์ธ์.
// ์ถ๊ฐ ์ต์
์ ์ฌ๊ธฐ์ ์ ๋ฌํด์ผํฉ๋๋ค.
// ์ง๊ธ์ ๊ฐ๋จํ๊ฒ ์ ์งํ๊ฒ ์ต๋๋ค.
const router = new VueRouter({
routes // `routes: routes`์ ์ค์
})
// 4. ๋ฃจํธ ์ธ์คํด์ค๋ฅผ ๋ง๋ค๊ณ mount ํ์ธ์.
// router์ router ์ต์
์ ์ ์ฒด ์ฑ์ ์ฃผ์
ํฉ๋๋ค.
const app = new Vue({
router
}).$mount('#app')
// ์ด์ ์ฑ์ด ์์๋ฉ๋๋ค!
๋ผ์ฐํฐ๋ฅผ ์ฃผ์
ํ์์ผ๋ฏ๋ก this.$router
์ ํ์ฌ ๋ผ์ฐํธ๋ฅผ this.$route
๋ก ์ ๊ทผํ ์ ์์ต๋๋ค.
// Home.vue
export default {
computed: {
username () {
// ๊ณง `params` ํ์ธํ ์ ์์ต๋๋ค.
return this.$route.params.username
}
},
methods: {
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
}
}
}
๋ฌธ์ ์ ์ฒด์์ router
๋ฅผ ์์ฃผ ์ฌ์ฉํ์ต๋๋ค. this.$router
๋ ์ ํํ router
์ ๋์ผํฉ๋๋ค. this.$router
๋ฅผ ์ฌ์ฉํ๋ ์ด์ ๋ ๋ผ์ฐํฐ๋ฅผ ์กฐ์ํด์ผํ๋ ๋ชจ๋ ์ปดํฌ๋ํธ์์ ๋ผ์ฐํธ ๊ฐ์ฒด๋ฅผ ๊ฐ์ ธ์ฌ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์
๋๋ค.
์ด ์์ ์์ ๋ฐ๋ก ํ์ธํด๋ณผ ์ ์์ต๋๋ค.
<router-link>
๋ ํ์ฌ ๋ผ์ฐํธ์ ์ผ์นํ ๋ ์๋์ผ๋ก .router-link-active
ํด๋์ค๊ฐ ์ถ๊ฐ๋ฉ๋๋ค. API ๋ ํผ๋ฐ์ค๋ฅผ ํ์ธํ์ธ์.