본문 바로가기
Script/vue.js

vue.js 컴포넌트간 통신

by BeGeek 2020. 1. 14.

1. 상위 컴포넌트에서 하위 컴포넌트로 데이터 전달 (props속성 활용)

<html>
  <head>
      <title>Vue Component Registration</title>
  </head>
  <body>
      <div id="app">
        <child-component v-bind:propsdata="message"></child-component>
      </div>

      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
      <script>
        Vue.component('child-component', {
          props: ['propsdata'],
          template: '<p>{{ propsdata }}</p>'
        });

        new Vue({
          el: '#app',
          data: {
            message : 'Hello Vue! passed from Parent Component'
          }
        });


      </script>
    </body>
  </html>

 

2. 하위에서 상위 컴포넌트로 이벤트 전달

<html>
  <head>
      <title>Vue Component Registration</title>
  </head>
  <body>
      <div id="app">
        <child-component v-on:show-log="printText"></child-component>
      </div>

      <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script>
      <script>
        Vue.component('child-component', {
          template: '<button v-on:click="showLog">show</button>',
          methods:{
            showLog: function(){
              this.$emit('show-log');
            }
          }
        });

        var app = new Vue({
          el: '#app',
          data: {
            message : 'Hello Vue! passed from Parent Component'
          },
          methods: {
            printText: function(){
              console.log("received an event");
            }
          }
        });


      </script>
    </body>
  </html>

'Script > vue.js' 카테고리의 다른 글

템플릿 속성(computed, method, watch)  (0) 2020.01.15
axios로 데이터 받아오기  (0) 2020.01.15
vue.js 개발환경 구성  (0) 2020.01.11

댓글