Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining user-defined getters in a Vue component

My question relates to Vue and more specifically reactivity and reactive getter/setters: https://v2.vuejs.org/v2/guide/reactivity.html

Can I define my own getters in a Vue component and what will happen to them when Vue add its own reactive getters?

like image 248
balteo Avatar asked Oct 30 '25 13:10

balteo


1 Answers

Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty

What the above sentence means is vue iterates over each property in your data option to make them reactive.

For example consider your data option to be:

data:{
  foo: 'hello world',
  bar: 3
}

vue will override the data object as follows(just an abstract description):

let key = Object.keys(data)

for (let i = 0; i < keys.length; i++) {
  let val = data[keys[i]];
  Object.defineProperty(data, keys[i], {
    get(){
      // add this property as a dependency when accessed
      return val;
    },
    set(newVal){
      //notify for a change
      val = newVal;
    }
  })
}

If you check out the vue source code for the same you will find that it checks whether the properties have predefined getters or setters.

Then it overrides the properties getter as follows:

Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: function reactiveGetter() {
    const value = getter ? getter.call(obj) : val;
    if (Dep.target) {
      dep.depend();
      if (childOb) {
        childOb.dep.depend();
        if (Array.isArray(value)) {
          dependArray(value);
        }
      }
    }
    return value;
  },
  set(newVal) {
    //...
  }
});

If you see this line const value = getter ? getter.call(obj) : val; you'll notice that if you defined a getter it is being used and is its value returned.

Vue is just doing some more work to make them reactive by invoking some dependency related methods thats it.

like image 181
Vamsi Krishna Avatar answered Nov 01 '25 05:11

Vamsi Krishna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!