Vue - Watch

h.Im·2024년 9월 10일
0

Vue 기초

목록 보기
21/28
post-thumbnail

종종 반응형 상태가 변경되었을때 다른 작업(api call 등)을 수행해야 하는 경우가 있습니다. watch 함수를 이용하면 반응형 상태가 변경될 때마다 특정 작업을 수행할 수 있습니다.

<template>
	<div></div>
</template>

<script>
import { ref, watch } from 'vue'
export default {
	setup() {
		const message = ref('')
		watch(message, (newValue, oldValue) => {
			console.log('newValue', newValue, 'oldValue', oldValue)
		})
		return { message }
	},
}
</script>

<style></style>

위처럼 코드를 작성 후 vue devtools 내에서 message 값을 변경하면 변경된 값이 newValue, 이전 값이 oldValue에 출력됨을 볼 수 있습니다. ref 뿐만 아니라 watch 함수의 첫 번째 매개변수는 다양한 타입이 될 수 있습니다.

  • ref
  • reactive
  • computed
  • getter 함수
  • array 타입
<template>
	<div></div>
</template>

<script>
import { ref, reactive, watch } from 'vue'
export default {
	setup() {
		const x = ref(0)
		const y = ref(0)
		const obj = reactive({
			count: 0,
		})
		// x와 y의 합을 얻는 getter를 작성한 유형
		watch(
			() => x.value + y.value,
			(newSum, oldSum) => {
				console.log(newSum, oldSum)
			},
		)
		// 배열을 첫 번째 인자로 사용한 유형
		watch([x, y], ([newX, newY]) => {
			console.log(newX, newY)
		})

		// object를 첫 번째 인자로 사용한 유형
		// object의 경우, 같은 객체를 가리키게 되어 newValue, oldValue가 동일하게 콘솔에 출력됨
		watch(obj, (newValue, oldValue) => {
			console.log(newValue, oldValue)
		})

		// object 내부의 값 하나만을 watch하고자 하는 경우, getter함수를 사용한다
		watch(
			() => obj.count,
			(newValue, oldValue) => {
				console.log('newValue', newValue, 'oldValue', oldValue)
			},
		)
		return { x, y, obj }
	},
}
</script>

<style></style>

object를 watch 함수의 첫 번째 인자로 사용한 예제를 통해 알 수 있는 내용은, object의 속성 뿐만아니라 모든 중첩된 속성에도 watch가 트리거된다는 사실입니다. 반면, getter 함수로 객체를 넘길 경우에는 객체의 값이 바뀔 경우에만 트리거 됩니다. 즉, 중첩된 속성은 트리거되지 않습니다.
watch 함수는 반응형 값이 변할 때에 트리거 되지만, watch의 콜백 함수가 즉시 실행되기를 원할 때도 있습니다. 이런 경우, immediate 옵션을 사용할 수 있습니다.

<template>
	<div></div>
</template>

<script>
import { ref, watch } from 'vue'
export default {
	setup() {
		const message = ref('Hello')
		const reverseMessage = ref('')
		// immediate 속성 때문에 화면이 로드되지마자 reverseMessage.value는 olleH이 됩니다.
		watch(
			message,
			(newValue) => {
				reverseMessage.value = newValue.split('').reverse().join('')
			},
			{
				immediate: true,
			},
		)
		return { message, reverseMessage }
	},
}
</script>

<style></style>

WatchEffect

콜백 함수 안의 반응형 데이터에 변화가 감지되면 자동으로 반응하여 실행됩니다. 그리고 WatchEffect의 코드는 컴포넌트가 생성될 때 즉시 실행됩니다.

<template>
	<form action="">
		<input v-model="title" type="text" placeholder="title" />
		<textarea v-model="contents" placeholder="contents"></textarea>
	</form>
</template>

<script>
import { ref, watchEffect } from 'vue'
export default {
	setup() {
		const title = ref('')
		const contents = ref('')
		watchEffect(() => {
			console.log('title.value', title.value)
			console.log('contents.value', contents.value)
		})
		return { title, contents }
	},
}
</script>

<style></style>

watchEffect 함수의 콜백함수 내부에 title, value가 존재할 뿐인데, 두 값이 v-model에 의하여 변경될 때마다 콘솔에 출력이 됩니다. watchEffect는 watch와 다르게, 렌더링 시 바로 한 번 호출됩니다.

0개의 댓글