解决vue双向绑定带来的问题

89 阅读1分钟

问题场景: 查询完表格数据后 通过作用域插槽,将该行数据传到修改页面(定义了个新对象存储数据),但是由于数据双向绑定,修改这个新对象的值,会影响到最初查询表格获取的值

image.png 如下

<el-button
    type="primary"
    icon="el-icon-edit"
    size="mini"
    @click="showEditDialog(scope.row)"
>编辑</el-button>

showEditDialog(row) {
    this.editForm = row
}

解决方案:

方法1:通过json之间的解析,深拷贝创建一个与row无绑定关联的临时对象,再赋值给editForm

this.editForm = JSON.parse(JSON.stringify(row))

方法2:使用…展开运算符

this.editForm = {...this.editForm,...row}

方法3:$set也不会影响原数据,但只能操作单个数据,在上述场景可能不太适用(属性多久麻烦了)

this.$set(this.editForm,'roleName',row.roleName)
this.$set(this.editForm,'roleDesc',row.roleDesc)

这样就不会影响到最初的row啦!