【问题标题】:Why is watch not reacting to changes of a property of an object in an Array of objects?为什么手表对对象数组中对象属性的更改没有反应?
【发布时间】:2022-01-06 21:31:29
【问题描述】:

考虑以下(简化的)商店。它包含一个“笔记”(类对象)数组:

// store.ts

import { reactive } from 'vue'
import { Note } from 'src/lib/note'

class Store {
  allNotes: Note[] = []
}
export const store = reactive(new Store())

我想关注allNotes 的变化:

// note.ts

import { store } from 'src/lib/store'
    
watch(store.allNotes,
  (oldVal, newVal) => _.difference(newVal, oldVal)
    .forEach(note => {
      console.log("note changed")
    }),
  {deep: true}
)

当更改特定注释(store.allNotes 元素的属性)时,我确实在 Chome DevTools Vue 中看到了更改,但我的手表没有触发。为什么?

【问题讨论】:

    标签: vue.js vuejs3 watch


    【解决方案1】:

    reactive 属性不会在 watch 方法中自动解包(与 ref 不同),因此您需要使用函数 watch(()=>store.allNotes,... 将它们返回:

    watch(()=>store.allNotes,
      (oldVal, newVal) => _.difference(newVal, oldVal)
        .forEach(note => {
          console.log("note changed")
        }),
      {deep: true}
    )
    

    【讨论】:

    • 谢谢,但这没有帮助。我将不得不深入挖掘以了解缺乏触发更改的情况 - 我认为 deep 足以监控属性。
    • 关于这个的一个问题:数组是反应性的,但它的元素也是反应性的(它们是通过.push() 添加的。或者应该以一种使它们反应性的方式添加它们?
    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2023-01-13
    • 2019-11-20
    • 2017-04-06
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多