[Vue.js 맛보기 feat.사전과제] 컴포넌트 생성과 이벤트 버스

1) 전역 컴포넌트 생성

<div id="app">
      <child-component></child-component>
</div>
<script>
    Vue.component('child-component', {
      props: ['propsdata'],
      template: '<button v-on:click="showLog">show</button>',
      methods: {
        showLog: function() {
          this.$emit('show-log')
        }
      }
    });
</script>

2) 지역 컴포넌트 생성

<div id="app">
      <local-component></local-component>
</div>
<script>
var cmp = {
	template: '<div> 전역 컴포넌트입니다.</div>',
};

new Vue({
	el: '#app',
    // 지역 컴포넌트 등록
    components: {
      'local-component': cmp
    }
)}
</script>

3) 컴포넌트 통신 ( 하위 -> 상위 )

    <div id="app">
      <child-component v-on:show-log="printText"></child-component>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script>
    Vue.component('child-component', {
      props: ['propsdata'],
      template: '<button v-on:click="showLog">show</button>',
      methods: {
        showLog: function() {
          this.$emit('show-log')
        }
      }
    });

    const app = new Vue({
      el: '#app',
      data: {
        message: "Hello Vue!"
      },
      methods: {
        printText: function() {
          console.log("received Event")
        }
      }
    });
    </script>

4) 컴포넌트 통신 - 이벤트 버스

    <div id="app">
      <child-component></child-component>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script>
    var eventBus = new Vue();

    Vue.component('child-component', {
      template: '<div>하위 컴포넌트 영역입니다.<button v-on:click="showLog">Show</button></div>',
      methods: {
        showLog: function() {
          eventBus.$emit('triggerEventBus', 100);
        }
      }
    });

    const app = new Vue({
      el: '#app',
      created: function() {
        eventBus.$on('triggerEventBus', function(value){
          console.log("이벤트를 전달받음. 전달받은 값 : ", value);
        });
      }
    });
    </script>

좋은 웹페이지 즐겨찾기