Vue 3 reactivity not triggered from inside a class instance

As another answer explains, reactive creates proxy object to enable the reactivity. this in constructor refers to original MyClass instance and not a proxy, so it cannot cannot be reactive.

This indicates the probem in the code. reactive takes into account synchronous operations that occur in MyClass constructor. It’s an antipattern to perform asynchronous side effects in a constructor , the reasons include possible implications with the code that consumes such constructor.

This can be solved with:

class MyClass {
  constructor(){
    // synchronous stuff only
    this.entries = ["a"];
  }

  init() {
    // asynchronous stuff, probably return a promise
    setTimeout(() => {
      this.entries.push("c");
    }, 1000);
  }
}

and

const myobject = reactive(new MyClass());
myobject.init() // `this` is a proxy inside `init`

Leave a Comment