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. p>
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(), }; }, };
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:In the options API it is:
In the composition API it is::