fix(reactivity): should not trigger watch on computed ref when value is unchanged
fix #2231
This commit is contained in:
@@ -13,7 +13,8 @@ import {
|
||||
DebuggerEvent,
|
||||
TrackOpTypes,
|
||||
TriggerOpTypes,
|
||||
triggerRef
|
||||
triggerRef,
|
||||
shallowRef
|
||||
} from '@vue/reactivity'
|
||||
|
||||
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
|
||||
@@ -750,8 +751,8 @@ describe('api: watch', () => {
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
test('should force trigger on triggerRef when watching a ref', async () => {
|
||||
const v = ref({ a: 1 })
|
||||
test('should force trigger on triggerRef when watching a shallow ref', async () => {
|
||||
const v = shallowRef({ a: 1 })
|
||||
let sideEffect = 0
|
||||
watch(v, obj => {
|
||||
sideEffect = obj.a
|
||||
@@ -785,4 +786,17 @@ describe('api: watch', () => {
|
||||
await nextTick()
|
||||
expect(spy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// #2231
|
||||
test('computed refs should not trigger watch if value has no change', async () => {
|
||||
const spy = jest.fn()
|
||||
const source = ref(0)
|
||||
const price = computed(() => source.value === 0)
|
||||
watch(price, spy)
|
||||
source.value++
|
||||
await nextTick()
|
||||
source.value++
|
||||
await nextTick()
|
||||
expect(spy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -161,9 +161,10 @@ function doWatch(
|
||||
}
|
||||
|
||||
let getter: () => any
|
||||
const isRefSource = isRef(source)
|
||||
if (isRefSource) {
|
||||
let forceTrigger = false
|
||||
if (isRef(source)) {
|
||||
getter = () => (source as Ref).value
|
||||
forceTrigger = !!(source as Ref)._shallow
|
||||
} else if (isReactive(source)) {
|
||||
getter = () => source
|
||||
deep = true
|
||||
@@ -242,7 +243,7 @@ function doWatch(
|
||||
if (cb) {
|
||||
// watch(source, cb)
|
||||
const newValue = runner()
|
||||
if (deep || isRefSource || hasChanged(newValue, oldValue)) {
|
||||
if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
|
||||
// cleanup before running cb again
|
||||
if (cleanup) {
|
||||
cleanup()
|
||||
|
||||
Reference in New Issue
Block a user