Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(#8728): only execute the dependArray function once #8734

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/core/observer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,13 @@ export function defineReactive (
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
const targetWatcher = Dep.target
if (targetWatcher) {
dep.depend()
if (childOb) {
const needDepend = Array.isArray(value) && !targetWatcher.checkRelated(childOb.dep)
childOb.dep.depend()
if (Array.isArray(value)) {
if (needDepend) {
dependArray(value)
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/core/observer/watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,13 @@ export default class Watcher {
}
}

/**
* Check if a dependency has been associated with the current watcher.
*/
checkRelated (dep: Dep) {
return this.newDepIds.has(dep.id)
}

/**
* Clean up for dependency collection.
*/
Expand Down
29 changes: 28 additions & 1 deletion test/unit/modules/observer/observer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
del as delProp
} from 'core/observer/index'
import Dep from 'core/observer/dep'
import { hasOwn } from 'core/util/index'
import { hasOwn, _Set as Set } from 'core/util/index'

describe('Observer', () => {
it('create on non-observables', () => {
Expand Down Expand Up @@ -356,6 +356,33 @@ describe('Observer', () => {
})
})

it('Array\'s getter is triggered multiple times, the Watcher should only associate with Dep once.', () => {
const data = {
arr: [{}]
}
observe(data)
// mock a watcher!
const watcher = {
newDepIds: new Set(),
addDep (dep) {
this.newDepIds.add(dep.id)
dep.addSub(this)
},
checkRelated: function (dep) {
return this.newDepIds.has(dep.id)
}
}
spyOn(watcher, 'checkRelated').and.callThrough()
Dep.target = watcher
data.arr
data.arr
Dep.target = null
expect(watcher.checkRelated.calls.count()).toBe(2)
const allCalls = watcher.checkRelated.calls.all()
expect(allCalls[0].returnValue).toBe(false)
expect(allCalls[1].returnValue).toBe(true)
})

it('warn set/delete on non valid values', () => {
try {
setProp(null, 'foo', 1)
Expand Down