Vue中如何实现studsSummary数组元素随studDetailed对象变更同步响应
解决方案
问题根源
你当前的实现不生效主要有以下几个常见原因:
$set代码没有和输入框的修改事件绑定,仅执行一次无法实现实时同步- 索引写死为
0,只能修改数组第一项,无法匹配你当前选中的学生 - 如果学生对象本身已经存在
name属性,不需要用$set,直接赋值即可,$set仅用于给响应式对象新增原本不存在的属性
两种实现方案
方案1:引用绑定(最简单,无额外代码)
利用JS对象的引用传递特性,选中学生时直接让studDetailed指向数组中的对应对象,修改时会自动同步原数组:
- 先在
data中新增字段存储选中学生的索引:
data: function(){ return{ studsSummary:[], studDetailed : { name: '', surname: ''}, selectedStudIndex: -1 // 新增字段,记录选中的学生索引 } }
- 选中学生的逻辑中修改赋值方式:
// index为当前选中学生在studsSummary数组中的下标 selectStudent(index) { this.selectedStudIndex = index // 直接指向数组中的对象,共用引用 this.studDetailed = this.studsSummary[index] }
- 输入框保持原有
v-model='studDetailed.name'绑定即可,修改内容时会自动同步到studsSummary对应项,v-for渲染的列表也会自动更新。
方案2:监听同步(适用于studDetailed需要额外独立字段的场景)
如果studDetailed需要存储不希望同步到摘要列表的额外字段,可以用监听实现同步:
- 同样先新增
selectedStudIndex存储选中索引,选中学生时单独赋值属性:
selectStudent(index) { this.selectedStudIndex = index // 单独赋值属性,不共用引用 this.studDetailed = { name: this.studsSummary[index].name, surname: this.studsSummary[index].surname, // 其他独立字段 } }
- 添加
watch监听studDetailed的属性变化,同步到数组:
watch: { 'studDetailed.name'(newVal) { if (this.selectedStudIndex < 0) return // 已存在的属性直接赋值即可触发响应式更新 this.studsSummary[this.selectedStudIndex].name = newVal }, 'studDetailed.surname'(newVal) { if (this.selectedStudIndex < 0) return this.studsSummary[this.selectedStudIndex].surname = newVal } }
注意:如果你使用的是Vue3,
$setAPI已经被移除,所有响应式属性直接修改即可,不需要额外调用API。
内容的提问来源于stack exchange,提问作者Justin Farrugia
相关产品推荐
相关产品推荐

