럿고의 개발 노트

[인프런] 웹 게임을 만들며 배우는 Vue 9. Vue Router 본문

Vue.js Note/[인프런] 웹 게임을 만들며 배우는 Vue(동영상 강의)

[인프런] 웹 게임을 만들며 배우는 Vue 9. Vue Router

KimSeYun 2019. 11. 19. 13:44

[인프런] 웹 게임을 만들며 배우는 Vue

9. Vue Router

9.1. Vue Router 설정하기

- npm i vue-router 설치

9.2. router-vue와 히스토리 라우터

9.3. 동적 라우트 매칭

9.4. 주소 쿼리스트링

- 예제(웹 게임)을 통해 Vue를 만나는 시간으로, 예제를 풀면서 주석으로 배운 내용과 알아야 할 내용을 최대한 적어 놓았습니다. 코드와 주석을 참고해주세요!. 노드와 웹팩을 사용하여 설정파일들이 존재합니다. 아래 깃허브를 참고해주세요.

[main.js]

1
2
3
4
import Vue from 'vue';
import router from './Router';
 
new Vue(router).$mount('#root');
cs



[package.json]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
  "name""mine-sweeper",
  "version""1.0.0",
  "description""",
  "main""index.js",
  "scripts": {
    "bulid""webpack --watch",
    "dev""webpack-dev-server --hot"
  },
  "author""",
  "license""ISC",
  "dependencies": {
    "vue""^2.6.10",
    "vue-loader""^15.7.2",
    "vue-router""^3.1.3",
    "vue-template-compiler""^2.6.10",
    "vuex""^3.1.2",
    "webpack""^4.41.2",
    "webpack-cli""^3.3.10"
  },
  "devDependencies": {
    "css-loader""^3.2.0",
    "vue-style-loader""^4.1.2",
    "webpack-dev-server""^3.9.0"
  }
}
 
cs


[webpack.config.js]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const path = require('path'); // 경로 불러오는 것
 
module.exports = { // 노드에 모듈을 만듬, 이안에 웹팩 모든 설정을 넣으면 됨.
    mode:'development'// 배포할건지 개발한건지
    devtool: 'eval'// 개발할때는 eval, 배포할때는 hid,den-source-map
    resolve: {
        extensions: ['.js''.vue'], // 이걸 하면 import할때 확장자를 넣어줄 필요가 없다.
    },
    entry: { // 스크립트를 모인것 중에서 대표적인 스크립트
        app : path.join(__dirname, 'main.js'), // app은 하나로 합친 스크립트 이름
    },
    module: { // 웹팩의 핵심 // entry로 처리하다가 이상한거 나오면 loader를 실행
        rules: [{ // 합칠때 어떻게 합칠지를 설정해주는 것
            test: /\.vue$/// .vue로 끝나는 파일은 vue-loader를 사용하겠다, 정규표현식
            loader: 'vue-loader'// npm i vue-loader
        },{
            test: /\.css$/
            use: [ // loader와 user는 똑같은 기능
                'vue-style-loader',
                'css-loader',
            ]
        }],
    },
    plugins: [
        new VueLoaderPlugin(),
    ],
    output: {
        filename: '[name].js'// 출력할 파일 이름(최종결과)
        path: path.join(__dirname, 'dist'), // 폴더 경로
        publicPath: '/dist'// webpack-dev-server 세팅시 필요
    },
};
 
// entry, module, plugins, output이 주 설정 나머지는 부가적인 설정
cs


[routes.js]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Vue from 'vue';
import VueRouter from 'vue-router';
import NumberBaseball from '../Chapter03/NumberBaseball';
import ResponseCheck from '../Chapter04/ResponseCheck';
import RockScissorsPaper from '../Chapter05/RockScissorsPaper';
import LottoGenerator from '../Chapter06/LottoGenerator';
import TicTacToe from '../Chapter07/TicTacToe';
import MineSweeper from '../Chapter08/MineSweeper';
import GameMatcher from './GameMatcher'
 
Vue.use(VueRouter);
 
export default new VueRouter({
  mode: 'history',
  routes: [
    { path: '/number-baseball', component: NumberBaseball },
    { path: '/response-check', component: ResponseCheck },
    { path: '/rock-scissors-paper', component: RockScissorsPaper },
    { path: '/lotto-generator', component: LottoGenerator },
    { path: '/tic-tac-toe', component: TicTacToe },
    { path: '/mine-sweeper', component: MineSweeper },
    { path: '/game/:name', component: GameMatcher } // ex) /game/number-baseball/
  ],
});
cs



[Router.html]


1
2
3
4
5
6
7
8
9
10
11
12
13
htm<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>라우터</title>
</head>
<body>
    <div id="root"></div>
    <script src ="dist/app.js"></script>
</body>
</html>
cs


[Router.vue]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
  <div>
    <div> <!-- 레이아웃으로, 바뀌지 않는 화면 -->
      <router-link to="/game/index">게임 매쳐</router-link>
      <!-- 주소 쿼리스트링(route에 query안에 key/value로 보여진다), 페이징할때 많이 사용하는 것이 아닐까 생각합니다 -->
      <router-link to="/game/number-baseball?data=1&hello=rutgo&bye=rutgo">숫자야구</router-link> <!-- 라우터내에 있던 주소를 적으면 링크가 됨 -->
      <router-link to="/game/response-check">반응속도</router-link> <!-- a링크와 동일하지만, 페이지가 변경되기보다는 컴포넌트가 변경된다고 생각하면 됨 -->
      <router-link to="/game/rock-scissors-paper">가위바위보</router-link>
      <router-link to="/game/lotto-generator">로또생성기</router-link> 
      <router-link to="/game/tic-tac-toe">틱택토</router-link>
      <router-link to="/game/mine-sweeper">지뢰찾기</router-link>
    </div>
    <router-view></router-view> <!-- 바뀌는 화면이 들어갈 공간 -->
  </div>
</template>
 
<script>
 
 
import router from './routes';
  
  export default {
    router,
  };
</script>
 
<style>
    table{
        border-collapse: collapse;
    }
    td{
        border: 1px solid black;
        width: 40px;
        height: 40px;
        text-align: center;
    }
</style>
 
cs



[GameMatcher.vue]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!-- 동적 라우트 매칭 -->
<template>
<div v-if="currentGame === 'number-baseball'">
    <number-baseball></number-baseball>
</div>
<div v-else-if="currentGame === 'response-check'">
    <response-check></response-check>
</div>
<div v-else-if="currentGame === 'lotto-generator'">
    <lotto-generator></lotto-generator>
</div>
<div v-else>일치하는 게임이 없습니다.</div>
</template>
 
<script>
import NumberBaseball from '../Chapter03/NumberBaseball';
import ResponseCheck from '../Chapter04/ResponseCheck';
import LottoGenerator from '../Chapter06/LottoGenerator';
 
 
export default {
    components: {
        NumberBaseball,
        ResponseCheck,
        LottoGenerator,
    },
    mounted() {
        console.log(this.$router); // 설정이 궁금하면 나오는 것
        console.log(this.$route); // 게임내에 있는 주소들이 들어있음
    },computed: {
        currentGame() {
            return this.$route.params.name;
        },
    },
};
</script>
cs






Comments