반응형

0. 들어가기

-. 오브젝트들의 구성 (컴포넌트)가 반복되는 경우 쉽게 사용할 수 있는 방법. C#에서 컴퓨넌트 모델이라고 부르던 그것인거같다.

1. 컴포넌트 작성

-. 컴포넌트마다 app.component('컴포넌트 이름', ~로 시작하는 별개의 vue.js 코드를 작성해야 한다.

-. Template: html 코드에 작성되어 있던 해당 컴포넌트 구성 <div> ~ </div>를 전부 복사해서 넣으면 된다. Javascript 특유의 ` ~ ` 표기를 써야한다.

    template:
    /*html*/
    `<div :style="{ backgroundColor: bgColor }">
    <button 
    :disabled="!calculation"
    v-on:click="addClicks">button</button> clicks = ( {{clicks}} )
    remain: {{ remained }} color: {{ bgColor }}
    </div>`

-. 이후 기존 코드에 있던 data, methods, computed 코드를 전부 그대로 붙여넣으면 된다.

app.component('count-display', {
    template:
    /*html*/
    `<div :style="{ backgroundColor: bgColor }"> //뒤에서 사용할 property에 대응하는 구문
    <button 
    :disabled="!calculation"
    v-on:click="addClicks">button</button> clicks = ( {{clicks}} )
    remain: {{ remained }} color: {{ bgColor }}
    </div>`,
    data() {
        return {
            clicks: 0,
            calculation: true,
            
        }
    },
    //함수정의
    methods: {
        addClicks() {
            this.clicks += 1;
        },


    },
    computed: {
        remained() {
            remained = 10 - this.clicks;
            this.calculation = (remained > 0);

            return remained
        },
    },
})

-. 이후 html 태그 사용하듯이 html 스크립트 내에 <component이름> 을 입력해주면 해당 컴포넌트가 표현된다.

                    <count-display></count-display>
                    <count-display></count-display>
                    <count-display></count-display>
                    <count-display></count-display>
                    
    <script src="./components/CountDisplay.js"></script>

-. 각 버튼의 기능이 개별적으로 동작하는 것을 확인할 수 있다.

2. 컴포넌트 프로퍼티 사용

-. 여러개 입력된 컴포넌트에 각기 다른 속성을 지정하고 싶으면 property라는 것을 지정해줘야 한다. html tag의 attribute와 비슷한 역할인 듯 한다. 위에서 작성한 app.component에 아래 구문을 추가한다.

    props: {
        redbackground: {
            type: Boolean,
            required: true,
        }
    },
    
    computed: {
    bgColor() {
        console.log(this.redbackground);
        if (this.redbackground) {
            return "red"
        }

        return "white"
    }

 -. 이후 html 코드에서 컴포넌트 호출을 할 때 해당 속성값을 지정해주면 된다. (위 코드는 redbackground란 것이 "true"면 빨강으로 표기되게 해주는 것.

                    <count-display redbackground="true"></count-display>
                    <count-display></count-display>
                    <count-display></count-display>
                    <count-display></count-display>
                    <count-display></count-display>

-. 출력을 보면 true로 지정된 버튼 블럭만 빨갛게 표시된다.

-. property 종류는 text, number, boolean 등이 있다. 링크참조.

728x90
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기