Vue 3 的 computed 天然支持依赖多个响应式输入值,只需在 getter 中直接读取 ref、reactive 属性、props 或其他 computed,Vue 自动追踪全部依赖并响应更新;需避免解构、动态 key、非响应式值等导致失效的写法。

Vue 3 的 computed 天然支持依赖多个响应式输入值,只要在 getter 函数中直接读取它们,Vue 就会自动追踪全部依赖,并在任一依赖变化时重新计算——不需要额外声明或数组传参,写法简洁且可靠。
直接在函数里读多个 ref 或 reactive 字段
你只需要把要用到的响应式变量(如 ref、reactive 对象属性、props、其他 computed)在箭头函数里访问,它们就会被自动收集为依赖:
- ✅ 正确示例:拼接姓名 + 年龄字符串
const firstName = ref('李')<br>const lastName = ref('四')<br>const age = ref(28)<br><br>const profileDesc = computed(() => `${firstName.value} ${lastName.value}(${age.value}岁)`)
只要 firstName、lastName 或 age 中任意一个更新,profileDesc.value 就会立刻重新生成。
组合 reactive 对象里的多个属性
如果数据来自 reactive,同样只需自然访问其字段:
- ✅ 示例:购物车商品总价 = 单价 × 数量
const product = reactive({<br> price: 99.9,<br> quantity: 3<br>})<br><br>const totalPrice = computed(() => product.price * product.quantity)
修改 product.price 或 product.quantity 都会触发 totalPrice 更新。注意:不能用解构赋值提前提取(如 const { price } = product),否则会丢失响应性。
跨层级组合多个来源的数据
computed 可混合使用不同来源的响应式数据,比如 ref + props + 另一个 computed:
- ✅ 示例:带折扣的最终价格
const basePrice = ref(100)<br>const discountRate = ref(0.1)<br>const isVip = computed(() => userStore.isVip) // 来自 store 的 computed<br><br>const finalPrice = computed(() => {<br> const rate = isVip.value ? discountRate.value * 1.5 : discountRate.value<br> return basePrice.value * (1 - rate)<br>})
所有被 .value 访问的响应式项都会纳入依赖链,逻辑清晰、可维护性强。
避免常见失效陷阱
以下写法会让多依赖“失效”,导致不更新:
- 用字符串动态 key 访问对象(如
obj[key],除非key本身是响应式且已参与计算) - 把非响应式普通对象或函数返回值(如
moment().format())直接用于计算 - 在计算中调用未包装成响应式的外部状态或副作用函数(如
fetch()、console.log()) - 把响应式数据先解构再使用(如
const { x } = reactiveObj→ 后续x不再响应)
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










