vue.js__전역 컴포넌트와 지역 컴포넌트 등록하기

박영은·2021년 11월 29일
0

vue

목록 보기
2/18

전역 컴포넌트 (Global component)

: 여러 인스턴스에서 공통으로 사용 가능.
(전역에서 확장자가 vue라면 import없이 모두 사용 가능. 상태 관리 contextAPI등과는 전혀 다른 개념임.)
: 사용 방법 = Vue 생성자에서 .component()를 호출.
= Vue.component('컴포넌트 이름', { // 컴포넌트 내용 })

ex) 사용 예시 
 
    	<template>
            <div id='test2'>
            	<button>컴포넌트 등록</button>
                <update-component></update-component>  (<-전역컴포넌트 표시)
            </div>
        </template>
    
    	<script>
            Vue.component('update-component', {
            	template: '<div>전역 컴포넌트 등록 완료!</div>'
            })
        </script>
        
        = '컴포넌트 등록' 버튼을 누르면 아래에 전역으로 선언한 'update-component'의
           template인 '전역 컴포넌트 등록 완료!' 부분이 출력된다.



지역 컴포넌트 (Local component)

: 특정 인스턴스에서만 사용 가능.
: 작성 예시)

new Vue({
 components: {
 	'컴포넌트 이름' : 컴포넌트 내용
 }
})
사용 예시) 

      <template>
      	<div id='test'>
           <h1>첫 번째 인스턴스 영역</h1>
           <button>컴포넌트 등록</button>
           <my-local-component>
           	<!-- 버튼 클릭 시 보여지는 지역 컴포넌트 
            		<div>지역 컴포넌트 입니다.</div>
                -->
           </my-local-component>
        </div>
        <div id='test2'>
           <h1>두 번째 인스턴스 영역</h1>
           <my-local-component>
           	<!-- 이렇게 적어두어도, 'test2'의 인스턴스에 지역 컴포넌트가
            	     선언된 것이 없기 때문에 아무것도 보여지지 않음 -->
           </my-local-component>
        </div>
      </template>
   
      <script>
      	var cmp = {
        	//컴포넌트 내용
            	template: '<div>지역 컴포넌트 입니다.</div>'
        };
        
        new Vue({
        	el: '#test',
            components: {
            	'my-local-component': cmp
            }
        });
        
        new Vue({
        	el: '#test2',
        });
      </script>
   



🔸 전역 컴포넌트는 인스턴스를 새로 생성할 때마다 인스턴스에 components속성으로 등록할 필요 없이 한 번 등록하면 어느 인스턴스에서든지 사용 가능함.
but, 지역 컴포넌트새 인스턴스를 생성할 때마다 등록해줘야 한다.

profile
Front-end

0개의 댓글