包邮状态没变,Vue 的 watch 为什么又跑了

作者:云间搭桥

时间:2026-12-05

浏览:337

购物车金额变了,包邮状态没变,Vue 的 watch 却又跑了一次。用三次金额变动查清新对象引用对回调的影响。

把示例购物车从 79 元加到 89 元,离包邮还差 10 元。free 还是 false,watch(freshBadge, ...) 的回调却会多跑一次。顺着 watch 的第一个参数找到 freshBadge,留意 getter 返回的那对花括号。

示例用的是 Vue 3.4 或更新版本。两边都按 99 元算包邮。每次改完金额都等一次 nextTick(),等这轮更新处理完再打印累计次数。

import { computed, nextTick, ref, watch } from 'vue'

const subtotal = ref(79)
const freshBadge = computed(() => ({ free: subtotal.value >= 99 }))
const stableBadge = computed(previous => {
  const free = subtotal.value >= 99
  if (previous && previous.free === free) return previous
  return { free }
})

const calls = { fresh: 0, stable: 0 }
watch(freshBadge, () => { calls.fresh += 1 })
watch(stableBadge, () => { calls.stable += 1 })

async function demo() {
  for (const amount of [89, 99, 109]) {
    subtotal.value = amount
    await nextTick()
    const { free } = stableBadge.value
    console.log(amount + ' free=' + free +
      ' fresh=' + calls.fresh + ' stable=' + calls.stable)
  }
}

demo()
VS Code 风格的 JavaScript 代码图,展示两种计算属性和回调计数。
两边共用同一条包邮规则,差别在返回的对象。
预期输出对照。金额为 89、99、109 元时,fresh 回调累计 1、2、3 次,stable 回调累计 0、1、1 次。
预期控制台输出。

先看 89 元那一行。两个 getter 都读了新金额,也都算出 false。freshBadge 又创建了一个 { free: false }。watch 拿到的对象和上次长得一样,引用已经换了。stableBadge 把上一次的对象交回来,监听到的值就没变。到了 99 元,free 变成 true,旧对象还保留着 false,两边的回调都会跑。

金额从 79 元变为 89 元,包邮状态相同。返回新对象使 watch 回调加一次,复用引用时次数不变。
从 79 元到 89 元,同样是未达到包邮门槛,两种写法的回调次数不同。

如果回调只在跨过包邮门槛时做点事,我会写成 watch(() => freshBadge.value.free, onFreeChange)。卡片可以继续用对象,watch 比较的是 getter 取出的布尔值。

要是卡片还显示「再买几元可包邮」,复用对象就得多看一项。79 元涨到 89 元,free 还是 false,差额已经从 20 元变成 10 元。先把这次要展示的字段算全,再决定能不能用回旧对象。这里如果只比 free,卡片就会继续显示还差 20 元。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章