vue computed
問題的例子如下
點擊查看例子
vue computed是計算屬性是基於它們的響應式依賴進行緩存的。只在相關響應式依賴發生改變時它們才會重新求值,依賴只監聽了一層和相關的依賴,對於數組對象這類的深層數據,就無法監聽到改變。
vue computed源碼在在初始化watch的時候沒有進行deep深層watch,
vue computed 源碼如下
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
// computed properties are just getters during SSR
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// 省略
}
}
解決方案
1.改用watch
2.修改數據到最頂層
let current = { ...this.list[index], num: newNum };
this.$set(this.list, index, current);
