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

Vue3如何检测数组中对象内部键的更新?附解决方案

Vue3数组内对象属性更新不触发视图更新的问题与解决

问题场景

模板代码:

<tr v-for="(object, index) in watchingArr" :key="index">
  <span>{{ object.1 }}{{ object.2 }} {{ object.3 }}</span>
</tr>
  • Vue3仅在数组长度变化且设置deep: true时能检测数组变化,但deep无法检测数组内对象的属性修改
  • Vue2中用于解决此类问题的Vue.set()在Vue3已弃用

代码对比

  • 有效代码(向数组添加新元素,能触发视图更新):
this.element[newKey] = newVal 
this.$store.dispatch('store/addElement', this.element) // 向watchingArr添加元素
  • 无效代码(仅更新数组内对象的键值,无法触发视图更新):
this.element[oldKey] = newVal 

补充:已确认实际数组已被更新,传递的是数组引用而非副本。

解决方案

该数组为Leaflet.js标记的数组,列表是独立的Vue3组件,处理步骤如下:

  1. 为Leaflet标记绑定Vue3自定义函数:
...
marker["customFunction"] = this.customFunction
...
},
customFunction() {
  // 修改store中的变量'updateList'
}
  1. 在标记的dragend事件中触发该自定义函数:
this.marker.on('dragend', function(event) {
  event.target.customFunction()
})
  1. 在列表组件中监听store的updateList变量,触发时调用this.forceUpdate()强制更新列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:40:13