2

I have a class which I use in my Vue3 component to set/reset/update some values with. I rely on Vue Watchers to see if my applied state is changed in said class to be able to do something with it (call an API endpoint for example).

Now this worked perfectly fine in Vue 2 but for some reason if I mutate a variable from inside my class it does not trigger my watch function. It DOES trigger my watch function when I set a value from my component however; but that option does not work for me in the long run.

So in short:

How can I make sure my watch is triggered when I set the value from my component AND from my Class instance itself?

Check my demo(And open console for some extra logging) to see what I mean: (expected behavior is that applied should be set to 3 in 1 second and 100 after 3 seconds) https://codepen.io/Timen/pen/JjLMawO

Things I've tried:

  • Using composition API and setup the watcher in my setup
  • Use watchEffect
  • Use deep: true and flush: post on watcher
  • Setting up an entire new project with no extra dependencies other than vite 3 + vue3 and even tried it with a clean build with vue-cli 4.5 + vue3
  • Wrapping my class in a ref() in my setup
  • Tried setting the applied value via Object.assign
CaptainCarl
  • 3,411
  • 6
  • 38
  • 71

1 Answers1

1

In Vue3, because of your data myClass is a TestClass instance's proxy, at 1 second, you watched the value myClass proxy, but at 3 second, you changed is the source data which you proxied, so you cannot watch the change of proxy source.

// in vue3
data:{
   a: b
   //means:a = new Proxy(b), you cannot watch the data b changes in vue or other observer.
}

It is not Vue3's shortage, it is proxy's specification

Finn
  • 101
  • 1
  • 7