Vue 09-2 Vue-CLI & router Project ๊ตฌํ˜„

Seungju Hwangยท2021๋…„ 1์›” 13์ผ
0

Vue

๋ชฉ๋ก ๋ณด๊ธฐ
11/18
post-thumbnail

Intro

$ vue create my-project

$ vue add router


router, views ํด๋” ๋ถ€๋ถ„์ด ์ถ”๊ฐ€๋จ!


๐Ÿ”ต ๊ตฌ์กฐํ™”

App.vue : ์ตœ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ !!
views/ : route(index.js) ์— ๋งคํ•‘๋˜๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ชจ์•„๋‘๋Š” ํด๋”
compotents/ : router์— ๋งคํ•‘๋œ ์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€์— ์ž‘์„ฑํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ๋“ค์„ ๋ชจ์•„๋‘๋Š” ํด๋”


๐Ÿ”ต ใ„ฑใ„ฑ

๋กœ๋˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ์•„์ฃผ ๊ฐ„๋‹จํ•œ ํŽ˜์ด์ง€๋ฅผ ๋งŒ๋“ค์–ด ๋ณผ๊ฒŒ์š”

  • ์šฐ์„  lodash ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์„ค์น˜ํ• ๊ฒŒ์š”
$vue add lodash

views/TheLotto.vue

์ปดํฌ๋„ŒํŠธ ๋งŒ๋“ค๊ธฐ

<template>
  <!--div์•ˆ์— ๋‹ค ๋„ฃ์–ด์ฃผ๋Š” ๊ฑธ ์„ ํ˜ธ-->
  <div>
    <h2>๋กœ๋˜๋ฒˆํ˜ธ ์ถ”์ฒœ</h2>
    <button @click="getLuckyNums">Pick My Lotto Numbers</button>
    <p>์˜ค๋Š˜์˜ ์ถ”์ฒœ ๋กœ๋˜ ๋ฒˆํ˜ธ</p>
    <p>{{ selectedLuckyNums }}</p>  
    
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'TheLotto',
  data: function () {
    return {
        sampleNums: [],
        selectedLuckyNums: [],
      }
  },
  methods: {
    getLuckyNums: function () {
      const numbers = _.range(1, 46)
      this.sampleNums = _.sampleSize(numbers, 6)

      this.selectedLuckyNums = _.sortBy(this.sampleNums)
      // this.selectedLuckyNums.sort(function (num1, num2) {
      //   return num1 - num2
      // })
    },
  }
}
</script>

<style>
</style>

router/index.js

๋ผ์šฐํ„ฐ(๋งํฌ) ๋“ฑ๋กํ•˜๊ธฐ

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
// 1.์ปดํฌ๋„ŒํŠธ ๋“ฑ๋กํ•˜๊ธฐ
import TheLotto from '../views/TheLotto.vue'

Vue.use(VueRouter)

//2. ์‹ค์ œ route(๊ฒฝ๋กœ)๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๋ฐฐ์—ด
const routes = [
  //...
  
  // 3. ๊ฒฝ๋กœ ์ •๋ณด ์ž‘์„ฑ
  {
    //3-1 ํŠน์ • ์ปดํฌ๋„ŒํŠธ์™€ ๋งคํ•‘๋œ ๊ฒฝ๋กœ
    path: '/lotto',
    //3-2 ๋ณ„๋ช…์œผ๋กœ ๋ถ€๋ฅผ ๋•Œ ์‚ฌ์šฉํ•  ์ด๋ฆ„
    name: 'TheLotto',
    //3-3 ๊ฒฝ๋กœ์— ๋งž๋Š” ํ™”๋ฉด์ด ๋ณด์—ฌ์งˆ ๋•Œ ๋‚˜ํƒ€๋‚˜๋Š” ๋Œ€์ƒ (์œ„์—์„œ importํ•œ ์ปดํฌ๋„ŒํŠธ)
    component: TheLotto
  }
]

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

export default router

App.vue

<template>
  <div id="app">
    <div id="nav">
      <!-- ... -->
      
      <!-- ๊ฒฝ๋กœ๋กœ ๋ถ€๋ฅด๋Š” ๋ฐฉ์‹ / ๋ณ„๋ช…์œผ๋กœ ๋ถ€๋ฅด๋Š” ๋ฐฉ์‹ -->  
      <router-link :to="{ name: 'TheLotto' }">TheLotto</router-link> 
    </div>
    <!-- 2. route outlet (์‹ค์ œ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง๋˜์–ด ๋ณด์—ฌ์ง€๋Š” ๊ณณ) -->
    <router-view/>
  </div>
</template>

output

์‚ฌ์šฉํ•˜์ง€ ์•Š์„ page ์‚ญ์ œํ•ด์ค์‹œ๋‹ค. ๊ฐ€๋ น ์œ„์—์„œ Home๊ณผ About!!

  • ์ปดํฌ๋„ŒํŠธ ์‚ญ์ œ!
  • index.js์— ๋“ฑ๋ก๋˜์–ด ์žˆ๋Š” ๋ผ์šฐํŠธ ์‚ญ์ œ!
  • App.vue์—์„œ ๊ฒฝ๋กœ ์‚ญ์ œ!

profile
๊ธฐ๋กํ•˜๋Š” ์Šต๊ด€์€ ์‰ฝ๊ฒŒ ๋ฌด๋„ˆ์ง€์ง€ ์•Š์•„์š”.

0๊ฐœ์˜ ๋Œ“๊ธ€