
computed에서 사용한다.computed는 default로 getter() 함수가 있지만 필요에 의해 setter() 함수를 설정할 수 있다.<template>
<p>원본 배열 : {{ arr }}</p>
<p>역순 배열 : {{ reverseArr }}</p>
</template>
<script>
export default {
data() {
return {
arr: [1, 2, 3, 4, 5]
}
},
computed: {
// getter
reverseArr: function () {
return [...this.arr].reverse()
}
}
}
</script>
🧐 computed와 methods 사용하는 방법이 같은데 차이점이 뭘까?
computedreverseArr의 종속 대상은 arrarr의 값이 바뀌지 않는다면 reverseArr를 여러번 호출해도 다시 계산하지 않고 캐싱한 결과를 즉시 반환한다.methodsmethods를 사용한다.computed 속성이 적합하지만 사용자가 특정 지정한 값을 감시하는 경우 watch 옵션을 사용한다.watch 옵션을 사용하여 상태 변경이 발생할 때 함수를 실행할 수 있다.<template>
<p v-if="isShow">질문에는 일반적으로 물음표가 포함됩니다.</p>
<span>질문 : </span>
<input :value="question" @input="questionInput" />
<p> answer : {{ answer }}</p>
</template>
<script>
export default {
data() {
return {
question: '',
answer: '',
isShow: true
}
},
watch: {
question(newQuestion) {
if (newQuestion) this.isShow = false;
else this.isShow = true;
if (newQuestion.indexOf('?') > -1) this.getAnswer()
}
},
methods: {
questionInput(event) {
this.question = event.target.value;
},
async getAnswer() {
this.answer = '생각 중...'
try {
const res = await fetch('https://yesno.wtf/api');
this.answer = (await res.json()).answer === 'yes' ? '네' : '아니오'
} catch (error) {
this.answer = `Error : ${error}`;
}
}
}
}
</script>
🧐 computed vs watch
computed를 사용하는 것이 적절하지만 watch를 사용해야 할 경우가 있다.computed는 선언형이고 , watch는 명령형이다.watch와 computed 비교// watch
data() {
return {
firstName: 'Dohee',
lastName: 'Kang',
fullName: 'Dohee Kang'
}
},
watch: {
// firstName이 바뀔 경우
firstName: function (value) {
this.fullName = `${value} ${this.lastName}`;
},
// lastName이 바뀔 경우
lastName: function (value) {
this.fullName = `${this.firstName} ${value}`;
}
}
// computed
data() {
return {
firstName: 'Dohee',
lastName: 'Kang'
}
},
computed: {
fullName: function () {
return `${this.firstName} ${this.lastName}`;
}
}