DevYoon
[Vue] 점심 메뉴와 로또 번호를 추천해보자 본문
1️⃣ App.vue 라우터 경로 설정
<template>
<div id="app">
<nav>
<router-link :to="{name:'lunch'}">Lunch</router-link> |
<router-link :to="{name:'lotto', params:{ lottoNum:6 }}">Lotto</router-link>
</nav>
<router-view/>
</div>
</template>
🔥 router-link to = '/lunch'
🔥 router-link :to = '{name:'lunch'}' ➡️ Named Routes
2️⃣ index.js routes 설정
const routes = [
{
path: '/lunch',
name: 'lunch',
// 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: lunch
},
{
path:'/lotto/:lottoNum',
name: 'lotto',
component:() => import('../views/lotto.vue')
}
]
🔥 component는 () => import(~) 혹은 컴포넌트 이름으로 가져올 수 있다.
3️⃣ Lunch
<template>
<div class="lunch">
<h1>점심메뉴</h1>
<button @click="choiceLunch">Pick Lunch</button>
<p>{{menu}}</p>
<h3>로또를 뽑아보자</h3>
<button @click='getLotto'>Pick Lotto</button>
</div>
</template>
<script>
import _ from 'lodash'
export default {
name:"LunchMenu",
data(){
return {
menu:""
}
},
methods: {
choiceLunch(){
this.menu = _.sample(['국밥', '파스타', '냉면', '치킨', '샐러드', '샌드위치'])
},
getLotto(){
this.$router.push({name:'lotto', params:{ lottoNum:6 }})
}
}
}
</script>
🔥 lodash sample ➡️ _.sample(collection) - collection에서 랜덤한 값 하나 반환
🔥 this.$router.push ➡️ 다른 URL로 이동
4️⃣ lotto
<template>
<div class="lotto">
<h1>로또</h1>
<button @click='getLotto'>Get Lucky Numbers</button>
<p>{{lottoNumbers}}</p>
</div>
</template>
<script>
import _ from 'lodash'
export default {
name:'lottoGet',
data(){
return{
lottoNumbers:""
}
},
methods:{
getLotto(){
this.lottoNumbers = []
const numbers = _.range(1, 46)
this.lottoNumbers = _.sampleSize(numbers, this.$route.params.lottoNum)
}
}
}
</script>
🔥 lodash range ➡️ _.range(start, end, step) - 범위 내 숫자로 이루어진 배열 생성
🔥 lodash sampleSize ➡️ _.sampleSize(collection, size) - 원하는 size만큼 랜덤 데이터 반환
🔥 this.$route.params ➡️ 동적 인자 전달
🔥 동적 인자는 :(콜론)으로 시작 ex) lotto/:lottoNum
🔥 컴포넌트에서 this.$route.params로 동적 인자 사용 가능