reactivity apis
reactive
- 모든 속성에 영향을 준다
- object가 아닌 proxy를 반환
const obj = reactive({ count: 0 })
ref
- ref object 반환하고 반응성을 반환하고 값을 반환함
- ref object 는 .value로 값을 가져옴
- 객체가 참조 값으로 할당되면 반응 방법에 의해 객체 반응
const count = ref(0)
console.log(count.value)
count.value++
console.log(count.value)
const count = ref(0)
const state = reactive({
count
})
console.log(state.count)
state.count = 1
console.log(count.value)
- 현재 ref에 연결된 값이 새로운 ref로 변경됨
- ref는 reative object에 있을때만 랩이 해제된다
const otherCount = ref(2)
state.count = otherCount
console.log(state.count)
console.log(count.value)
- array나 collection 타입과 같은 것을 접근할 때 랩을 해체하는 행동이 아니다
const arr = reactive([ref(0)])
console.log(arr[0].value)
const map = reactive(new Map([['foo', ref(0)]]))
console.log(map.get('foo').value)
computed
- getter 함수를 가져오고 불변의 반응성 ref object를 반환
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value)
plusOne.value++
- 대안으로, get,set 함수로 object 가져올 수 있음
const count = ref(1)
const plusOne = computed({
get: () => count.value + 1,
set: val => {
count.value = val - 1
}
})
plusOne.value = 1
console.log(count.value)
readonly
- 일반, 반응성 객체를 가져오고 읽기만 가능한 proxy를 반환
const original = reactive({ count: 0 })
const copy = readonly(original)
watchEffect(() => {
console.log(copy.count)
})
original.count++
copy.count++
watchEffect
- 반응성을 트래킹하며 즉시 함수 시작
- 의존적인게 바뀌게 되면 바로 re-run
const count = ref(0)
watchEffect(() => console.log(count.value))
setTimeout(() => {
count.value++
}, 100)
- watcher 멈추는 법
- setup() 함수를 부르는 동안 watcheffect가 호출됨
- 컴포넌트 생명주기에 watcher 이 연결 되어 있고 자동적으로 컴포넌트가 unmounted될때 멈춤
const stop = watchEffect(() => {
})
stop()
watchEffect(onInvalidate => {
const token = performAsyncOperation(id.value)
onInvalidate(() => {
token.cancel()
})
})
- DOM에서 watch를 사용하고 싶으면 mounted 훅에서 사용
onMounted(() => {
watchEffect(() => {
})
})
- watcher 동기 이거나 컴포넌트가 업데이트 된 후 효과가 있음
watchEffect(
() => {
},
{
flush: 'sync'
}
)
watchEffect(
() => {
},
{
flush: 'pre'
}
)
- watcher debugging
- onTrack, onTrigger 옵션이 디버그 watcher 행동을 해줌
- onTrack - 반응성 property가 호출되거나 ref가 의존되어있을 때
- onTrigger - watcher반환하거나 변화가 의존되어있을 때
- 두개의 callback는 debugger event 반환함
watchEffect(
() => {
},
{
onTrigger(e) {
debugger
}
}
)
watch
- 구체적인 데이터 자원을 요구하고 각각의 콜백 함수에 단점이 적용된다
- watched할 데이터가 변화가 있을때만 call 된다
- 한개의 데이터
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
}
)
const count = ref(0)
watch(count, (count, prevCount) => {
})
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
})