티스토리 뷰
웹사이트를 살펴보면 일정한 양식으로 반복되는 객체를 볼 수 있다. 쇼핑몰에서 상품을 소개할 때 보면 일정한 양식으로 반복되는 객체를 쉽게 찾아 볼수 있다. 상품에 대한 사진, 가격, 이름 등 해당 상품에 필요한 필수 정보들을 담고 있어야 한다. 상품에 대한 정보를 데이터베이스에 넣고, 데이터를 부를 수 있는 변수를 지정한다. 그리고 변수를 객체로 넣어주면 자동으로 계산되어 웹 사이트가 만들어 진다면 이를 쉽게 구현할 수 있다.
위에 사진과 동일하게 3개의 반복되는 객체를 만들게 된다면 이를 컴포넌트로 제작 할 수 있다. 위 사진을 컴포넌트를 사용하지 않고, HTML으로 작성하면 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <div> <h3>Components box 1</h3> <button type="button" name="button" class="btn">button1</button> <button type="button" name="button" class="btn">button2</button> </div> <div> <h3>Components box 2</h3> <button type="button" name="button" class="btn">button1</button> <button type="button" name="button" class="btn">button2</button> </div> <div> <h3>Components box 3</h3> <button type="button" name="button" class="btn">button1</button> <button type="button" name="button" class="btn">button2</button> </div> | cs |
이처럼 반복되는 코드 사용은 개발자로서 불편함을 야기시킨다. 이 요소들을 Vue.js의 컴포넌트로 관리해보자. Vue.js의 컴포넌트는 다음과 같은 구성요소를 가진다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | Vue.component('box-component',{ props:{ message:{ type: String, required: true, default: "Hello world!" } }, template: '<div> <h3>Components Box</h3> <button class="btn">button1</button> <button class="btn">button2</button> </div>' data() { return this.message } }) | cs |
- props : 하위 컴포넌트로 데이터를 전달하게 되는 경우 사용한다.
- template : 컴포넌트의 양식에 대한 정보
- data : 컴포넌트에서 노출 시킬 데이터
만약 처음에 살펴 본 웹 페이지를 컴포넌트로 선언하게 되면 Vue 인스턴스에 다음과 같이 선언하면 된다.
1 2 3 4 5 6 | Vue.component('box-component',{ template: '<div> <h3>Components Box</h3> <button class="btn">button1</button> <button class="btn">button2</button> </div>' }) |
그리고, HTML 코드에 컴포넌트를 선언한다.
1 2 3 4 5 | <div> <box-component></box-component> <box-component></box-component> <box-component></box-component> </div> | cs |
그리고 컴포넌트로 데이터를 전달하는 작업도 가능하다. message라는 변수를 컴포넌트로 전달하는 방법은 다음과 같다.
1 2 3 4 5 6 7 8 9 10 | Vue.component('box-component',{ props: ['message'], data:function () { return { message: '', } }, template: '<div><h3>{{ message }}</h3> <button class="btn">button1</button><button class="btn">button2</button></div>', }); | cs |
그리고 message 내용을 HTML의 속성으로 전달한다.
1 2 3 4 5 | <div> <box-component message="Components 1"></box-component> <box-component message="Components 2"></box-component> <box-component message="Components 3"></box-component> </div> | cs |
'Skill > Programming - Server & Client' 카테고리의 다른 글
12.[Nuxt.js] 프로젝트, 설정, 라우팅 (0) | 2020.01.27 |
---|---|
11.[Nuxt.js] 개념 및 소개 (0) | 2020.01.19 |
9.[Vue.js] 클래스, 스타일 바인딩 (0) | 2019.12.31 |
8.[Vue.js] 이벤트 핸들링 (0) | 2019.12.21 |
7.[Vue.js] 조건부 렌더링, 리스트 렌더링 (0) | 2019.12.15 |
댓글