vue中父子组件中对象传递问题


 问题的产生

做一个员工管理系统demo,修改选中的数据时,需要从父组件中传递过来一个员工对 象。子组件直接用props中定义的用于接收父组件传过来的值来展示,并且使用 :value.sync来绑定数据,这时候如果更改传入子组件中的值时,父组件的值也会改变,并且是自动更新。但是我并不想要这种结果。

如何解决

我们可以在子组件中定义一个新的对象,在子组件的init方法中给这个对象赋值,注意:两个对象不能直接“=”赋值,这样只是对象传递,新对象还是指向父组件传递过来的对象,不能解决问题,我们应该一个字段一个字段的给新对象赋值

methods:{

//初始化
init(var1) {
this.employeeData1.EID=this.employeeData.EID;
this.employeeData1.ENAME=this.employeeData.ENAME;
this.employeeData1.EDEPARTMENTID=this.employeeData.EDEPARTMENTID;
this.employeeData1.EGENDER=this.employeeData.EGENDER;
this.employeeData1.EAGE=this.employeeData.EAGE;
this.employeeData1.EDATE=this.employeeData.EDATE;
this.employeeData1.EADDRESS=this.employeeData.EADDRESS;
this.employeeData1.ETEL=this.employeeData.ETEL;
this.employeeData1.EREMARK=this.employeeData.EREMARK;
this.employeeData1.ESTATE=this.employeeData.ESTATE;
}
}

 

新的问题产生

经过运行代码又发现了新的问题,就是如果新增的时候,必须点击两次新增才能够获取到父组件传过来的值。我想应该是init方法和传值的过程是同时进行的,所以才导致第二次才能获取到传递的值。那么我们为什么不能把想传递的值直接放在init方法中呢?

methods:{
        
          //初始化
        init(var1,info) {
            this.employeeData1.EID=info.EID;
            this.employeeData1.ENAME=info.ENAME;
            this.employeeData1.EDEPARTMENTID=info.EDEPARTMENTID;
            this.employeeData1.EGENDER=info.EGENDER;
            this.employeeData1.EAGE=info.EAGE;
            this.employeeData1.EDATE=info.EDATE;
            this.employeeData1.EADDRESS=info.EADDRESS;
            this.employeeData1.ETEL=info.ETEL;
            this.employeeData1.EREMARK=info.EREMARK;
            this.employeeData1.ESTATE=info.ESTATE;
        }
}        

 


这样就解决了上述问题!
结论:父子组件传值如果不是修改或者说不需要数据校验,那么当然可以直接调用,但是如果涉及数据校验,不能随便传值,那么就需要新的对象接收传过来的值并且展示了!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM