computed property란
어휘 그대로 계산하는 속성이다. 보이기는 함수처럼 보이지만 사용할때는 속성처럼 사용한다. 값을 저장하기 보다 값을 계산하는 속성으로 문법이다.
메서드일 경우는 항상 호출되고 로직이 실행되지만 속성일 경우는 그 값이 변하지 않는 이상 캐쉬되므로 성능 향상에 잇점이 있다.
data 속성에 brand라는 키를 추가한다. 그리고, title이라는 computed property를 추가한다.
1 2 3 4 5 6 7 8 9 10 11 12 |
... data: { product: 'Socks', brand: 'Vue Mastery', ... computed: { title() { return this.brand + ' ' + this.product; } }, methods: { ... |
그리고 h1 에 product 왼편에 brand를 추가하기 위해서 expression을 두개 연달아 사용할 수 있다. {{ brand }} {{ product }} 이것을 조금전에 추가한 title computed property로 다음과 같이 사용한다.
1 2 3 4 |
... <div class="product-info"> <h1>{{title}}</h1> ... |
image 속성 => computed property로 변경
selectedVariant: 0 의 키 값을 추가한다.
updateProduct 메서드에서 index를 받아서 업데이트한다. 그리고
data에 image 속성을 제거하고 image를 computed property로 변경한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
... data: { product: 'Socks', brand: 'Vue Mastery', selectedVariant: 0, ... }, computed: { ... image() { return this.variants[this.selectedVariant].variantImage; }, ... }, methods: { ... updateProduct(index) { this.selectedVariant = index; } } }); |
updateProduct에 index를 넘기도록 html을 수정한다.
1 2 3 4 5 6 7 8 9 |
... <div class="color-box" v-for="(variant, index) in variants" :key="variant.variantId" :style="{ backgroundColor: variant.variantColor }" @mouseover="updateProduct(index)" > </div> ... |
마우스 오버를 해보면서 테스트해본다.
inStock 속성 => computed property 로 변경
variants 배열에 variantQuantity를 추가한다.
inStock 속성을 data에서 제거하고 computed property를 추가한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
var app = new Vue({ el: '#app', data: { ... variants: [ { variantId: 2234, variantColor: 'green', variantImage: 'https://www.vuemastery.com/images/challenges/vmSocks-green-onWhite.jpg', variantQuantity: 10 }, { variantId: 2235, variantColor: 'blue', variantImage: 'https://www.vuemastery.com/images/challenges/vmSocks-blue-onWhite.jpg', variantQuantity: 0 } ], cart: 0 }, computed: { ... inStock() { return this.variants[this.selectedVariant].variantQuantity; } }, ... }); |
+ todo
boolean 타입의 onSale 키의 data 속성을 추가한다. brand, product, onSale을 모두 합쳐서 sale이라는 computed property를 만들되 onSale이 true일때는 ” are on sale!” 을 false 일때는 ” are not on sale” 스트링을 출력하도록 한다.
h1 태그에 걸어도 좋고 혹은 그 아래 아무데나 걸어도 좋다.
See the Pen Challenge 7 – Intro to Vue by Gregg Pollack (@GreggPollack) on CodePen.0