Vue 스터디
Vue 스터디 2일차 (뷰 컴포넌트)
옹재
2021. 4. 29. 21:54
728x90
반응형
뷰 컴포넌트
대부분의 프론트엔드 프레임워크는 컴포넌트 기반으로 개발을 하고 있습니다. 컴포넌트는 화면의 영역을 영역별로 구분해서 코드로 관리하는 것이라고 볼 수 있습니다. 컴포넌트의 핵심은 재사용성
이라고 볼 수 있습니다.
전역 컴포넌트 등록 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<app-header></app-header>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
//Vue.component('컴포넌트 이름', 컴포넌트 내용)
//전역 컴포넌트(실제 서비스를 개발할 때는 전역 컴포넌트를 사용하는 일은 거의 없음)
Vue.component("app-header", {
template: "<h1>Header</h1>",
});
Vue.component("app-content", {
template: "<div>content</div>",
});
new Vue({
el: "#app",
});
//인스턴스를 생성하면 일반적으로 루트 컴포넌트가 됩니다.
</script>
</body>
</html>
지역 컴포넌트 등록 예제
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<app-footer></app-footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: "#app",
components: {
//'컴포넌트 이름' : 컴포넌트 내용
//지역 컴포넌트 등록방식
"app-footer": {
template: "<footer>footer</footer>",
},
},
});
</script>
</body>
</html>
지역 컴포넌트 vs 전역 컴포넌트
Vue.component('컴포넌트 이름', 컴포넌트 내용)
components: {
'컴포넌트 이름' : 컴포넌트 내용
}
- 지역 컴포넌트 : 해당 컴포넌트 아래에 어떤 컴포넌트가 들어갔는지 vue 개발자 도구에서 바로 확인이 가능하다.
- 전역 컴포넌트 : 플러그인이나 라이브러리 같은 전역으로 사용해야할 경우에만 전역으로 등록한다.
컴포넌트와 인스턴스
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<app-header></app-header>
<app-footer></app-footer>
</div>
<div id="app2">
<app-header></app-header>
<app-footer></app-footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("app-header", {
template: "<h1>Header</h1>",
});
new Vue({
el: "#app",
components: {
"app-footer": {
template: "<footer>footer</footer>",
},
},
});
new Vue({
el: "#app2",
});
</script>
</body>
</html>
위와 같이 전역 컴포넌트는 모든 인스턴스에 등록이 되어있습니다. 하지만 지역 컴포넌트는 인스턴스를 생성할 때 마다 등록을 해줘야합니다.
728x90
반응형