Home > database >  Understanding reactivity work technically?
Understanding reactivity work technically?

Time:09-14

I work with a simple store (see code). And it works very well. So I can change data in a RouterView and it will be changed immediately in a Navigation Component. It sounds like an observer pattern to me, doesn't it?

// store.js
import { reactive } from 'vue'

export const store = reactive({
    gender: "",
    name: "",
});

Question: But I would like to know how it works and how the same would look like in Vanilla JS.

CodePudding user response:

According to the documentation:

In Vue 3, Proxies are used for reactive objects and getter / setters are used for refs.

The page also provides pseudo-code:

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      track(target, key)
      return target[key]
    },
    set(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
}
  • Related