2018년 9월 10일

오늘 한 일:

내일 할 일:

Vue tutorial

vue 어플리케이션은 Vue 인스턴스에서 시작한다. vue는 MVVM 패턴에서 많은 영감을 받아 탄생했다. 컨벤션으로서 vue 인스턴스 변수를 vm(viewModel)로 칭한다. Vue 인스턴스 생성방법은 아래와 같다

let vm = new Vue({
    ...options
})

Options

인스턴스 생성시에 사용되는 객체

data

let vm = new Vue({
    data: ...
})

Vue 인스턴스가 고유하게 같는 속성. 변경될 경우 re-render된다. 주의할 점은 초기에 생성될 당시 없었던 속성이 추가되는 경우는 렌더링 되지 않는다.

data 인스턴스 속성외에도 $접두어를 통해 Vue가 제공하는 인스턴스 속성에 접근할 수 있다

vm.$watch('a', function (newValue, oldValue) {
  // This callback will be called when `vm.a` changes
})

lifecycle hook

인스턴스가 생성되기까지 여러 과정을 거치는데, 특정 단계에서 호출될 수 있게 하는 함수를 lifecycle hook이라고 한다. react와 비슷하게 created, beforemounted, updated와 같은 것들이 있다.

new Vue({
  data: {
    a: 1
  },
  created: function () {
    // `this` points to the vm instance
    console.log('a is: ' + this.a)
  }
})

template syntax

vue는 인스턴스의 데이터와 DOM을 바인딩하기 위해 선언적인 template 문법을 사용한다.

interpolation

directives

v-가 붙는 특별한 속성들을 directives라고 한다. single js expression이 사용되며 속성의 변화를 DOM에 적용시킨다

<div v-if='seen'>im here</div>

shorthand

v-bind:href > :href

v-on:click > @click

computed properties and watchers

computed properties

getter처럼 쓰일 수 있는 속성. data의 속성을 복잡한 로직을 처리해서 가져와야 할 경우 사용. 일반적인 속성처럼 사용된다

let vm = new Vue({
    el: 'app',
    data: { message: 'hello'},
    computed: {
        reverseMessage() {
            return this.message.split('').reverse().join('');
        }
    }
})
console.log(vm.message) // hello
console.log(vm.reverseMessage) // olleh
<div id='app'></div>

computed property vs methods

method를 이용해서 똑같은 결과를 얻을 수 있다

methods: {
	reverseMessage() {
		return this.message.split('').reverse().join('');
    }    
}
<div id='app'></div>

차이점은 computed property는 캐싱을 사용한다는 점이다. 의존하고 있는 데이터(여기서는 message)가 변경되지 않으면 다시 계산하지 않고 캐싱된 데이터를 리턴한다

computed vs watched property

computed setter

computed 속성은 기본으로 getter이지만 원한다면 setter도 설정할 수 있다

computed: {
    printMessage: {
        get() { return ...},
        set(newMessage) {
            this.message = newMessage
        }
    }
}
vm.printMessage = 'im changed';

class and style

v-bind:class를 이용하면 클래스를 조작할 수 있다.

<div v-bind:class='{activated: isActive}'></div>
<div v-bind:class='classObject'</div>
const vm = new Vue({
    el: '',
    data: {
        isActive: true,
        classObject: { return {}}
    },
    computed: {
        classObject(){ return {} }
    }
})

array syntax

배열을 이용해 여러 클래스를 적용시킬 수 있음

<div v-bind:class="[{active: isActive}, bluestyle, redstyle]"></div>

inline-style

v-bind의 style을 이용해서 css처럼 사용할 수 있다

<div v-bind:style='{color: activeColor, width: per + "%" }'></div>
data : {
    activeColor: 'blue',
    per: 50
}

style객체를 직접 바인딜 할 수도 있다

<div v-bind:style='styleObject'></div>
data: {
    styleObject: {
        color: 'blue',
        width: '50%'
    }
}

배열을 이용해서 style객체를 넘겨줄 수도 있다

<div v-bind:style='[styleObj1, styleObj2]'></div>