Vue.js 간단정리 #9 Vue Communicating Events

Jake Seo·2020년 5월 14일
0

Vue.js-간단정리

목록 보기
9/10

Vue.js 간단정리 #9 Vue Communicating Events

Intro

https://www.vuemastery.com/courses/intro-to-vue-js 에 정리된 공식 Vue 무료 강의에 있는 내용을 짧게 정리해보려 한다.

이벤트 커뮤니케이션이란?

이전에 컴포넌트라는 개념을 배웠고, 독립적인 오브젝트가 각각의 컴포넌트로 구현이 되는 것을 알았다.

이렇게 컴포넌트 단위로 단일 페이지를 구축하다보면 한가지 문제가 생길 때가 있는데,

바로 컴포넌트끼리 무언가 데이터를 공유하고 싶을 때 문제가 생긴다.

그럴 때 이러한 이벤트 커뮤니케이션이라는 행위를 하게 된다.

컴포넌트끼리 정보를 공유하려면?

아래와 같은 상황에서, 전체 버튼을 누른 횟수를 계산한다고 가정해보자.

<!DOCTYPE html>
<html lang="en">
  <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>TEST!!</title>
  </head>
  <body>
    <div id="app">
      <colorbutton color="red"></colorbutton>
      <colorbutton color="blue"></colorbutton>
      <colorbutton color="green"></colorbutton>
      <div>전체 버튼을 누른 횟수 : {{totalCount}}</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      // 컴포넌트는 Vue 메인 오브젝트 앞에 선언해야 함
      Vue.component('colorbutton', {
        props: {
          color: {
            type: String,
            required: true,
            default: 'red',
          },
        },
        template: `<div>
                    <button @click="addCount" :style="{color:color}">{{color}}</button>
                    <span>{{color}}버튼을 누른 횟수 : {{count}}</span>
                  </div>`,
        data() {
          return {
            count: 0,
          };
        },
        methods: {
          addCount() {
            this.count += 1;
          },
        },
      });

      var app = new Vue({
        el: '#app',
        data: {
          totalCount: 0,
        },
      });
    </script>
  </body>
</html>

현재는 아래와 같은 상황이다.

아무리 개별 컴포넌트 버튼을 눌러도 전체 버튼을 누른 횟수는 증가하지 않는다.

전체 버튼을 누른 횟수를 증가시키려면 어떻게 해야 할까?

답은 아래와 같다.

<!DOCTYPE html>
<html lang="en">
  <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>TEST!!</title>
  </head>
  <body>
    <div id="app">
      <colorbutton color="red" @increase-count="increaseTotalCount"></colorbutton>
      <colorbutton color="blue" @increase-count="increaseTotalCount"></colorbutton>
      <colorbutton color="green" @increase-count="increaseTotalCount"></colorbutton>
      <div>전체 버튼을 누른 횟수 : {{totalCount}}</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      // 앞에 선언해야 함
      Vue.component('colorbutton', {
        props: {
          color: {
            type: String,
            required: true,
            default: 'red',
          },
        },
        template: `<div>
                    <button @click="increaseCount" :style="{color:color}">{{color}}</button>
                    <span>{{color}}버튼을 누른 횟수 : {{count}}</span>
                  </div>`,
        data() {
          return {
            count: 0,
          };
        },
        methods: {
          increaseCount() {
            this.count += 1;
            this.$emit('increase-count');
          },
        },
      });

      var app = new Vue({
        el: '#app',
        data: {
          totalCount: 0,
        },
        methods: {
          increaseTotalCount() {
            this.totalCount += 1;
          },
        },
      });
    </script>
  </body>
</html>

해답은 this.$emit에 있는데, emit을 해줌으로써 메소드가 발생하는 순간을 캣치할 수 있다. 메소드가 발생하는 순간에 상위 컴포넌트의 콜백함수를 실행시키면, 하위 컴포넌트에서 발생한 메소드가 상위 컴포넌트에 영향을 미칠 수 있다.

increaseCount() {
  this.count += 1;
  this.$emit('increase-count');
},

위에서 emit을 해주고

<colorbutton color="red" @increase-count="increaseTotalCount">

위에서 콜백 함수를 먹여주는 것이다.

결과로 아래와 같이 표기할 수 있다.

모든 버튼을 누른 횟수도 잘 나온다.

profile
풀스택 웹개발자로 일하고 있는 Jake Seo입니다. 주로 Jake Seo라는 닉네임을 많이 씁니다. 프론트엔드: Javascript, React 백엔드: Spring Framework에 관심이 있습니다.

0개의 댓글