[vue] reactivity

해피데빙·2022년 12월 21일
0
  1. Reactivity
    : a programming paradigm that allows us to adjust to changes in a declarative manner
  1. How reactivity works in vue
    js에서 객체 속성을 읽고 쓸 때 intercept하는 두가지 방법
  • getter/setters
  • proxy

vue2 : getter/setters
vue3: proxy (reactive objects), getter/setters (refs)

  1. 작동 방법 의사코드
function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      track(target, key)
      return target[key]
      //변경된 값을 가져온다
    },
    set(target, key, value) {
    //target에 요소가 들어오고 변경한 key에 변경한 value를 넣는다
      target[key] = value
      trigger(target, key)
    }
  })
}

function ref(value) {
  const refObject = {
    get value() {
      track(refObject, 'value')
      return value
    },
    set value(newValue) {
      value = newValue
      trigger(refObject, 'value')
    }
  }
  return refObject
}

limitations of reactive objects

  • When you assign or destructure a reactive object's property to a local variable, the reactivity is "disconnected" because access to the local variable no longer triggers the get / set proxy traps.
  • The returned proxy from reactive(), although behaving just like the original, has a different identity if we compare it to the original using the === operator.

track()

  • check whether there is a currently running effect
  • if there is one, we lookup the subscriber effects (stored in a Set)
    //다른 변수의 반응형을 팔로우하는
    for the property being tracked and add the effect to Set
let activeEffect

function track(target, key){
  if(activeEffect){
   conset effects = getSubscribersForProperty(target, key) 
   effects.add(activeEffect) 
  }
}
profile
노션 : https://garrulous-gander-3f2.notion.site/c488d337791c4c4cb6d93cb9fcc26f17

0개의 댓글