vue,两个接口给两个不同的对象进行赋值,修改第一个对象时,第二个对象也发生改变是怎么回事?

getCatalog().then((res)=>{
                    this.formInline.projectId = res.data.items
                    this.form.projectId = res.data.items
                })
                getPopularize().then((res)=>{
                    this.formInline.popularize = res.data
                    this.form.sourceAccountId = res.data
                })
// 点击修改用户
            uplodeClick(index,row){
                console.log(row)
                this.dialogVisible = true
                this.form.id = row.id;
                this.form.mobile = row.userName
                this.form.projectId.id = row.projectId
                this.form.sourceAccountId.code = row.source
            },

QQ截图20200526172335.png

阅读 3.1k
2 个回答
新手上路,请多包涵

来个深拷贝. 试试

因为接口的返回值是一个对象,你直接 = 号赋值,相当于两个变量的this指向都是对同一个对象的引用,所以如果你修改了其中的某一个,因为对象赋值是地址的引用,所以另外一个对象也就改变了。
解决方案:

1、简单一点的就是 JSON.parse(JSON.stringify(res.data))

2、如果你的对象层级不是有深层嵌套的,可以使用 Object.assign({}, res.data) 来给两个变量赋值;如果有深层嵌套,不推荐这个

3、深拷贝方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题