[Vue.js試用feat.先行タスク]構成部品とイベントバスの作成

15847 ワード

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>