You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中watch监听数组splice操作无响应,填充数组时正常

Vue中数组splice操作未触发watch监听的解决方法

问题原因

你当前的watch仅监听filter.organization的引用地址变化:

  • splice是数组的原地变异方法,只会修改数组内部元素,不会改变数组本身的引用,所以默认的浅监听不会触发回调。
  • 数组填充操作如果是直接赋值新数组(如filter.organization = [新元素]),会改变数组引用,因此能正常触发watch。

解决方法

方法一:开启深度监听

给watch添加deep: true配置,让监听器能检测到数组内部元素的变化:

watch(
  () => filter.organization,
  (newVal) => {
    console.log(newVal, 'filter');
  },
  { deep: true }
);

方法二:监听数组长度(按需选择)

如果只需要感知数组元素数量的变化,可以直接监听数组的length属性:

watch(
  () => filter.organization.length,
  (newLength) => {
    console.log(newLength, '数组长度变化');
  }
);

方法三:替换为新数组(避免深度监听)

如果业务允许,删除元素时返回一个新数组,通过改变引用触发watch:

// 点击事件代码替换为:
filter.organization = filter.organization.filter((_, i) => i !== index);

内容的提问来源于stack exchange,提问作者Salil Rajkarnikar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:11:02