[Vue.js] computed 속성과 장점
computed 속성은 템플릿의 데이터 표현을 더 직관적이고 간결하게 도와주는 속성입니다.
computed 속성에는 2가지 장점이 있습니다.
1. (템플릿에 데이터 표현을 넣지 않음으로 인해) 템플릿의 가독성이 증가합니다.
2. computed 내의 연산에 들어있는 변수값이 바뀌면 자동으로 재연산이 됩니다.
예시
<!DOCTYPE html> <p>{{ num }}</p> <p>{{ doubleNum }}</p> </div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> new Vue({ el: '#app', data: { num: 10 }, computed: { doubleNum: function() { return this.num * 2; } } }) </script> |
화면에서 오래걸리는 계산식을 소스 바꿀때마다 재연산이 안되게 하려면, computed에서 연산식을 선언하여 리턴 받아야됩니다.
그러면 관련된 변수 값이 변하지 않는 한, 재연산을 하지 않게 됩니다.
사용방법
<div> 평균 시간: {{average}}ms </div> |
export default { data() { return { result: [], ... } }, computed: { average() { return this.result.reduce((a, c) => a + c, 0) / this.result.length || 0; // 초기값은 0 } } } |
주의사항은 computed안에 처리할 변수(result) 앞에 'this.'을 붙여줘야 됩니다.
출처 : 1) joshua1988.github.io/vue-camp/syntax/computed.html
2) https://www.youtube.com/watch?v=5-e2NZGiz_c&list=PLcqDmjxt30RsdnPeU0ogHFMoggSQ_d7ao&index=19
소스 출처 : Vue.js 시작하기 - Age of Vue.js