Vue.js 인스턴스 & 컴포넌트

인스턴스 생성

Vue.js의 모든 앱은 인스턴스를 만드는 것부터 시작됩니다. 인스턴스를 생성하고, 인스턴스 안에 el속성으로 화면과 뷰 인스턴스를 연결하고 data 속성으로 화면에 표시될 메시지를 출력할수 있습니다.

image


인스턴스 속성

뷰 인스턴스를 생성할때, data, el, template 등의 속성을 지정하여 정의할 수 있습니다. el 속성은 인스턴스가 주입되는 화면 컴포넌트와 연결되며, data 속성은 데이터를 전달하기 위해 사용됩니다.

image


인스턴스 유효 범위

인스턴스의 유효범위는 el 속성에 지시한는 <div> 태그 내로 국한됩니다. 아래와 같이 message가 인스턴스 범위를 벗어나면 data의 메시지는 정상적으로 출력 되지 않습니다.

image


뷰인스턴스 라이프사이클

뷰 인스턴스의 라이프사이클은 beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed 충 8단계를 가지며 아래의 그림과 같습니다.

The Vue Instance Lifecycle


컴포넌트

컴포넌트는 화면을 블록 단위로 구조화하여 일정 단위로 쪼개서 재활용 가능한 형태(</>태그)로 관리하며, 직곽적으로 이해하기 편리합니다.

image


전역등록

Vue 생성자에서 componet 함수를 호출하여 전역 컴포넌트를 등록할 수 있습니다.

<html>
  <head>
    <title>Vue Component</title>
  </head>
  <body>
    <div id="app">
      <my-component></my-component>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
      Vue.component( 'my-component',{
        template: '<div>사용자 정의 전역 컴포넌트 입니다!</div>'
      });
      new Vue({
        el: '#app'
      });      
    </script>
  </body>
</html>

위 예제를 실행하면 다음과 같은 화면이 출력됩니다.

image


지역 컴포넌트

모든 컴포넌트를 전역으로 등록 할 필요는 없습니다. 컴포넌트를 components 인스턴스 옵션으로 등록함으로써 다른 인스턴스/컴포넌트의 범위에서만 사용할 수있는 컴포넌트를 만들 수 있습니다

<html>
  <head>
    <title>Vue local Component</title>
  </head>
  <body>
    <div id="app">
      <my-local-component></my-local-component>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
      var cmp= {
        template: '<div>사용자 정의 지역 컴포넌트 입니다!</div>'
      }
      new Vue({
        el: '#app',
        components: {
          'my-local-component': cmp
        }
      });
    </script>
  </body>
</html>



상/하위 컴포턴트 관계

상위 하위 컴폰넌트 관계는 트리구조에서 부모 노드 자식노드 처럼 부모 자식 관계로 이루어진 컴포넌트를 말합니다. 기존적으로 자식간에 데이터를 직접 전달하는 것은 불가능하며, 기본적으로 부모 자식 간의 컴포넌트는 데이터를 전달할 수 있습니다. 부모 컴포넌트는 자식컨포넌트에 props라는 속성을 통해 전달하고, 자식은 이벤트를 통해 부모에게 데이터를 전달합니다.

image


상위(부모)에서 하위(자식) 컴포넌트로 데이터 전달하기

하위 컴포넌트에 props 속성을 지정하고, props 속성에 대한 이름을 지정하고 상위 컴포넌트 데이터 속성에 연결합니다.

image

<html>
  <head>
    <title>Vue Component</title>
  </head>
  <body>
    <div id="app">
      <child-component v-bind:propsdata="message"></child-component>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
      Vue.component( 'child-component',{
        props: [ 'propsdata' ],
        template: '<p>{{propsdata}}</p>'
      });
      new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue!!'
        }
      });
    </script>
  </body>
</html>


하위(자식)에서 상위(부모) 컴포넌트로 데이터 보내기

자식 컴토넌트에서 부모컴포넌트로 이벤트를 발생시켜 데이터를 보내고, 부모컨포넌트 이벤트를 수신하여 데이터를 수신할 수 있습니다.

image

<html>
  <head>
    <title>Vue Component</title>
  </head>
  <body>
    <div id="app">
      <child-component v-on:show-log="printText"></child-component>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
      Vue.component( 'child-component',{
        template: '<button v-on:click="showLog">show</button>',
        methods:{
          showLog: function(){
            this.$emit('show-log','send-data');
          }
        }
      });
      new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue!!'
        },
        methods:{
          printText: function( obj ){
            alert(obj);
          }
        }
      });
    </script>
  </body>
</html>


컨포넌트간 통신

서로 관계가 없는 컨포넌트 간에도 이벤트버스를 사용하여 데이터를 주고 받을 수 있습니다.

<html>
  <head>
    <title>Vue Component</title>
  </head>
  <body>
    <div id="app">
      <child-component></child-component>
    </div>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script>
      var eventBus = new Vue();
      Vue.component( 'child-component',{
        template: '<button v-on:click="showLog">show</button>',
        methods:{
          showLog: function(){
            eventBus.$emit('show-log','send-data');
          }
        }
      });
      new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue!!'
        },
        created: function(){
          eventBus.$on( 'show-log' , function(obj){
            alert('receive data:'+obj);
          })
        }
      });
    </script>
  </body>
</html>

댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

스타트업 성장 곡선 The Startup Curve

[정보] 인스타그램은 당신의 소리를 '듣고' 있을 수도 있습니다

현수막/명함 등 인쇄물 디자인하기