💻 it/development

[Vue.js] 컴포넌트(재사용 유용)

꼬비랩 2025. 11. 20.

컴포넌트 등록

전역 컴포넌트 등록(플러그인이나 라이브러리 형태로 사용 시)

Vue.component('app-header', {   
    template: '<header>header</header>'
});

지역 컴포넌트 등록(일반적인 컴포넌트)

1.
new Vue({
  el: '#app2',
          //아래 components(s붙여야 함) 속성 이용(복수 )
    components: {
        'app-footer': {
            template: '<footer>footer</footer>'
        }                
    }
})

2.
//가독성을 위해 컴포넌트 내용을 object를 만들어서 전달
let appFooter = {
    template: '<footer>footer</footer>'
}
new Vue({
  el: '#app2',
    components: {
        'app-footer': appFooter 
    }
})

지역컴포넌트는 인스턴스트를 적용한 엘리먼트안에서만 적용됨

<div id="app">  
    <app-header></app-header>      
    <app-footer></app-footer>
</div>

<!-- <app-header>(전역 컴포넌트)는 #app2에 적용이 되지만 
<app-footer>(지역 컴포넌트)는 적용되지 않고 에러 발생(Unknown custom element: <app-footer>...) -->
<div id="app2">
<app-header></app-header>      
<app-footer></app-footer>
</div>

컴포넌트 적용

<div id="app">  
    <!-- 스크립트에서 등록한 컴포넌트명으로 태그를 설정 -->		
<app-header></app-header>      
</div>

전체코드

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Componet</title>
</head>
<body>

<!-- #app은 root component -->    
<div id="app">  
<!-- 아래에서 생성한 컴포넌트를 적용(하위/자식 컴포넌트) -->
<app-header></app-header>      

<!-- 데이터 바인딩 표현식 -->
<h2>{{ message }}</h2>

<app-content></app-content>  
<app-footer></app-footer>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
//전역 컴포넌트 생성(1번 째 인자: 컴포넌트명, 2번 째 인자: 객체(컴포넌트 내용, template 속성 이용))
Vue.component('app-header', {   
    template: '<header>header</header>'
});
Vue.component('app-content', {
    template: '<article>content</article>'
});

new Vue({
    el: '#app',
    //지역 컴포넌트 등록
    components: {
        'app-footer': {
            template: '<footer>footer</footer>'
        }                
    },
    //데이터 세팅
    data: {
        message: 'Hello Vue.js!!!!!!!'
    }                
})

</script>

</body>
</html>

결과

Root 컴포넌트를 기준으로 계층구조를 이룸

image source: https://v2.ko.vuejs.org/v2/guide/components.html

 

컴포넌트 — Vue.js

Vue.js - 프로그레시브 자바스크립트 프레임워크

v2.ko.vuejs.org

  • 부모 컴포넌트에서 자식 컴포넌트로는 props 속성으로 데이터 전달
  • 자식 컴포넌트에서 부모 컴포넌트로는 event로 데이터 전달

통신 규칙이 있으면 데이터 흐름 추적이 용이함

reference: https://www.inflearn.com/course/age-of-vuejs/dashboard

 

Vue.js 시작하기 - Age of Vue.js - 인프런 | 강의

Vue.js로 쉽게 웹 개발할 수 있도록 기본 개념과 핵심 기능에 대해서 학습하고 구현해봅니다. 강좌를 들으시고 나면 Vue.js로 프런트엔드 개발을 하시는게 재밌어질거에요., [사진] Vue.js 시작하기,Ag

www.inflearn.com

댓글