(VueJS v3) 我如何观察反应式数组的数组突变(插入、删除、替换)?
如何观察反应式数组,以便知道调用 push()
、splice()
等时插入、删除和替换的内容?
How can I watch a reactive array so that I know what is inserted, removed and replaced when push()
, splice()
, etc is called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于 splice 等不会直接为数组分配新值,因此 Vue 的反应性系统不会接收到更改,并且观察者不会触发。
但是,您可以创建一个复制数组的计算对象,然后观察:
演示
Since
splice
etc doesn't directly assign a new value to the array, Vue's reactivity system won't pick up on the changes and the watcher won't fire.You can, however, create a computed that copies the array and then watch that:
Demo
在 Vue3 上,您可以在脚本上执行此操作
,或者在 Vue 2 和 Vue3 上使用 Option API,
如果您使用 2 个解决方案,请不要忘记添加深度,否则它将无法在子数组上工作
On Vue3 you can do this on your script
Or on Vue 2 and Vue3 with Option API
if you use 2 solutions you don't forget to add deep otherwise it won't work on child array
也许这会有所帮助 (deep: true):
没有 'deep: true' vue3 不会检测数组 (props.options) 内容的更改。它仅检测“选项”的完全重新分配。使用“deep: true”,您可以推送/unshft/slice 等,正在调用处理程序 updateModelValueInternal。
Maybe that will help (deep: true):
Without 'deep: true' vue3 is not detecting changes of array (props.options) content. It detects only complete reassignment of 'options'. With 'deep: true' you can push/unshft/slice etc, the handler updateModelValueInternal is being invoked.