简体   繁体   English

更改 class 中的值不会触发 Vue 3 中的手表

[英]Changing value in a class does not trigger watch in Vue 3

I have a class which I use in my Vue3 component to set/reset/update some values with.我有一个 class 我在我的 Vue3 组件中使用它来设置/重置/更新一些值。 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).我依靠 Vue Watchers 来查看我应用的 state 是否在所述 class 中发生了变化,以便能够对其进行处理(例如,调用 API 端点)。

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.现在这在 Vue 2 中工作得非常好,但由于某种原因,如果我从 class 内部改变一个变量,它不会触发我的手表 function。 It DOES trigger my watch function when I set a value from my component however;但是,当我从组件设置值时,它确实会触发我的手表 function; 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?当我从组件和 Class 实例本身设置值时,如何确保触发手表?

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检查我的演示(并打开控制台以获取一些额外的日志记录)以了解我的意思:(预期的行为是应在 1 秒内将applied设置为 3,在 3 秒后设置为 100) https://codepen.io/Timen/pen/ JjLMawO

Things I've tried:我尝试过的事情:

  • Using composition API and setup the watcher in my setup使用组合 API 并在我的设置中设置观察者
  • Use watchEffect使用watchEffect
  • Use deep: true and flush: post on watcher使用deep: trueflush: post
  • 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设置一个全新的项目,除了 vite 3 + vue3 之外没有其他依赖项,甚至尝试使用 vue-cli 4.5 + vue3 进行干净构建
  • Wrapping my class in a ref() in my setup在我的setup中将我的 class 包装在ref()
  • Tried setting the applied value via Object.assign尝试通过Object.assign设置应用值

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.在 Vue3 中,由于你的数据myClass是一个TestClass实例的代理,在 1 秒,你看到了myClass代理的值,但是在 3 秒,你改变的是你代理的源数据,所以你不能看到代理源的变化。

// 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不是 Vue3 的不足,是proxy的规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM