包邮状态没变,Vue 的 watch 为什么又跑了
购物车金额变了,包邮状态没变,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()


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

如果回调只在跨过包邮门槛时做点事,我会写成 watch(() => freshBadge.value.free, onFreeChange)。卡片可以继续用对象,watch 比较的是 getter 取出的布尔值。
要是卡片还显示「再买几元可包邮」,复用对象就得多看一项。79 元涨到 89 元,free 还是 false,差额已经从 20 元变成 10 元。先把这次要展示的字段算全,再决定能不能用回旧对象。这里如果只比 free,卡片就会继续显示还差 20 元。
Vue.js 中利用递归组件实现动态菜单数据绑定
2026-12-04
Vue 3 自定义指令写法:生命周期钩子与注册方式
2026-12-04
常用JS前端框架有哪些:React、Vue与Angular核心对比
2026-12-04
Vue.js中怎么通过v-model双向绑定获取表单数据
2026-12-01
Vue中引入普通JS文件时this指向丢失的处理方法
2026-12-01





