Vue3 does not react to internal updates of class fields like Vue2 does
P粉274161593
P粉274161593 2024-01-29 12:45:06
0
1
359

I noticed that in Vue2 you can bind an element to a property of a class and the element will update when such property changes from somewhere outside the Vue world, but this is not the case in Vue3 It seems impossible.

I've created two simple examples here to illustrate what I mean:

Vue2:https://codesandbox.io/s/vue2-6hztv

Vue3:https://codesandbox.io/s/vue3-o2rfn

There is a class that has an internal timer that will increment the class field. In Vue2, the element bound to myClass.field is updated correctly, but in Vue3 nothing happens.

my question is

<强>1. Why is there a difference between Vue2 and Vue3 here?

<强>2. How can I achieve something like the Vue2 example but in Vue3?

Please note that I cannot run timers within Vue lifecycle methods. Class fields need to update themselves.

This is the Vue3 code that doesn't work:

HTML:

<div id="app">{{ myClass.field }}</div>

Javascript:

class MyClass {
  field = 0;

  constructor() {
    setInterval(() => {
      this.field++;
    }, 1000);
  }
}

export default {
  data() {
    return {
      myClass: new MyClass(),
    };
  },
};

P粉274161593
P粉274161593

reply all(1)
P粉709644700

As mentioned in this answer, create a proxy object in Vue 3 to enable reactivity. this in the constructor refers to the original class instance rather than the proxy, so it cannot be reactive.

The solution is to separate the class constructor and the side effect settings that expect this to be reactive. The setup method enables a fluent interface pattern, making it easier to use:

class MyClass {
  field = 0;

  init() {
    setInterval(() => {
      this.field++;
    }, 1000);

    return this;
  }
}

In the options API it is:

data() {
    return {
      myClass: new MyClass(),
    };
  },
  created() {
    this.myClass.init();
  }

In the composition API it is::

const myClass = reactive(new MyClass()).init();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template