Просмотр исходного кода

fix: remove wrong observe toggle, properly disable tracking in setup()

Evan You 4 лет назад
Родитель
Сommit
2d67641656
2 измененных файлов с 30 добавлено и 3 удалено
  1. 3 3
      src/v3/apiSetup.ts
  2. 27 0
      test/unit/features/v3/apiSetup.spec.ts

+ 3 - 3
src/v3/apiSetup.ts

@@ -1,6 +1,6 @@
 import { Component } from 'types/component'
 import { PropOptions } from 'types/options'
-import { toggleObserving } from '../core/observer'
+import { popTarget, pushTarget } from '../core/observer/dep'
 import { def, invokeWithErrorHandling, isReserved, warn } from '../core/util'
 import VNode from '../core/vdom/vnode'
 import {
@@ -31,7 +31,7 @@ export function initSetup(vm: Component) {
     const ctx = (vm._setupContext = createSetupContext(vm))
 
     setCurrentInstance(vm)
-    toggleObserving(false)
+    pushTarget()
     const setupResult = invokeWithErrorHandling(
       setup,
       null,
@@ -39,7 +39,7 @@ export function initSetup(vm: Component) {
       vm,
       `setup`
     )
-    toggleObserving(true)
+    popTarget()
     setCurrentInstance()
 
     if (isFunction(setupResult)) {

+ 27 - 0
test/unit/features/v3/apiSetup.spec.ts

@@ -267,4 +267,31 @@ describe('api: setup context', () => {
       }
     }).$mount()
   })
+
+  it('should not track dep accessed in setup', async () => {
+    const spy = vi.fn()
+    const msg = ref('hi')
+
+    const Child = {
+      setup: () => {
+        msg.value
+        return () => {}
+      }
+    }
+
+    new Vue({
+      setup() {
+        return h => {
+          spy()
+          return h(Child)
+        }
+      }
+    }).$mount()
+
+    expect(spy).toHaveBeenCalledTimes(1)
+
+    msg.value = 'bye'
+    await nextTick()
+    expect(spy).toHaveBeenCalledTimes(1)
+  })
 })