Front-end/Vue
Vue.js) Watch
ljs981026
2024. 7. 24. 17:12
1. Watch
데이터 속성이나 계산된 속성의 변화를 감지하여 특정 작업을 수행할 수 있는 기능입니다. watch를 사용하면 데이터의 변화를 반응적으로 처리할 수 있으며, 비동기 작업이나 외부 API 호출, 데이터 검증 등 다양한 작업을 할 수 있습니다.
2. 사용 예제
<template>
<h4 v-on:click="changeMessage">{{ msg }}</h4>
<h4>{{ reversedMessage }}</h4>
</template>
<script>
export default {
data() {
return {
msg: 'Hello?',
};
},
computed: {
reversedMessage() {
return this.msg.split('').reverse().join('');
},
},
watch: {
msg(newVal) {
console.log('msg: ', this.msg, ', newVal: ', newVal)
},
reversedMessage(newVal) {
console.log('reversedMessage: ', this.reversedMessage, ', newVal: ', newVal);
},
},
methods: {
changeMessage() {
this.msg = 'Good!';
},
},
};
</script>
h2 태그를 클릭 시 msg 값이 바뀌는 함수를 호출하면 msg와 reversedMessage에 기존 값이 변경되었기 때문에 watch 기능이 수행됩니다. watch에 명시할 때 위와 같이 매개변수를 따로 설정하여 불러올 수 도 있고 this를 통해 직접 접근할 수도 있습니다.
참고 문서:
https://v2.ko.vuejs.org/v2/guide/computed.html#watch-%EC%86%8D%EC%84%B1