reactivity apis

reactive

  • 모든 속성에 영향을 준다
  • object가 아닌 proxy를 반환
const obj = reactive({ count: 0 })

ref

  • ref object 반환하고 반응성을 반환하고 값을 반환함
  • ref object 는 .value로 값을 가져옴
  • 객체가 참조 값으로 할당되면 반응 방법에 의해 객체 반응
const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1
  • 템플릿에서 사용할때는 .value를 사용할 필요 없음

  • 반응성 객체 접근

    ref는 반응성 객체를 접근 변경하기 위해서는 자동으로 랩이 해제되어 일반 속성 처럼 동작

const count = ref(0)
const state = reactive({
  count
})

console.log(state.count) // 0

// state.count.value =1 -> X
state.count = 1
console.log(count.value) // 1
  • 현재 ref에 연결된 값이 새로운 ref로 변경됨
  • ref는 reative object에 있을때만 랩이 해제된다
const otherCount = ref(2)

state.count = otherCount
console.log(state.count) // 2
console.log(count.value) // 1
  • array나 collection 타입과 같은 것을 접근할 때 랩을 해체하는 행동이 아니다
const arr = reactive([ref(0)])
// need .value here
console.log(arr[0].value)

const map = reactive(new Map([['foo', ref(0)]]))
// need .value here
console.log(map.get('foo').value)

computed

  • getter 함수를 가져오고 불변의 반응성 ref object를 반환
const count = ref(1)
const plusOne = computed(() => count.value + 1)

console.log(plusOne.value) // 2

plusOne.value++ // error
  • 대안으로, 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) // 0

readonly

  • 일반, 반응성 객체를 가져오고 읽기만 가능한 proxy를 반환
const original = reactive({ count: 0 })

const copy = readonly(original)

watchEffect(() => {
      // 반응성 관련 일
  console.log(copy.count)
})

// 원본 변경시 사본 감지
original.count++

// 실패 하고 그리고 경고를 반환
copy.count++ // warning!

watchEffect

  • 반응성을 트래킹하며 즉시 함수 시작
  • 의존적인게 바뀌게 되면 바로 re-run
const count = ref(0)

watchEffect(() => console.log(count.value))
// -> logs 0

setTimeout(() => {
  count.value++
  // -> logs 1
}, 100)
  • watcher 멈추는 법
    • setup() 함수를 부르는 동안 watcheffect가 호출됨
    • 컴포넌트 생명주기에 watcher 이 연결 되어 있고 자동적으로 컴포넌트가 unmounted될때 멈춤
const stop = watchEffect(() => {
  /* ... */
})

// later
stop()
  • 무효화의 단점
    • 가끔 watched 함수는 비동기의 단점임
watchEffect(onInvalidate => {
  const token = performAsyncOperation(id.value)
  onInvalidate(() => {
    // id has changed or watcher is stopped.
    // invalidate previously pending async operation
    token.cancel()
  })
})
  • DOM에서 watch를 사용하고 싶으면 mounted 훅에서 사용
onMounted(() => {
  watchEffect(() => {
    // access the DOM or template refs
  })
})
  • watcher 동기 이거나 컴포넌트가 업데이트 된 후 효과가 있음
// fire synchronously
watchEffect(
  () => {
    /* ... */
  },
  {
    flush: 'sync'
  }
)

// fire before component updates
watchEffect(
  () => {
    /* ... */
  },
  {
    flush: 'pre'
  }
)
  • watcher debugging
    • onTrack, onTrigger 옵션이 디버그 watcher 행동을 해줌
    • onTrack - 반응성 property가 호출되거나 ref가 의존되어있을 때
    • onTrigger - watcher반환하거나 변화가 의존되어있을 때
    • 두개의 callback는 debugger event 반환함
watchEffect(
  () => {
    /* side effect */
  },
  {
    onTrigger(e) {
      debugger
    }
  }
)

watch

  • 구체적인 데이터 자원을 요구하고 각각의 콜백 함수에 단점이 적용된다
  • watched할 데이터가 변화가 있을때만 call 된다
  • 한개의 데이터
// watching a getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)

// directly watching a ref
const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})
  • 여러개 데이터 - array 이용
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  /* ... */
})

'Vue.js > vue3' 카테고리의 다른 글

[vue3] Reactivity Utilities  (0) 2020.09.30
[vue3] composition API  (0) 2020.09.30
[vue3] setup  (0) 2020.07.02
[vue3] vue 2 > vue3  (0) 2020.07.02

+ Recent posts