父组件中:
<child :value="parentform"></child>
data () {
return {
parentform: {
a: '1'
}
}
},
子组件中:
props: {
value: {
default:{},
required: false,
type: Object,
},
}
data () {
return {
form: {
a: '1',
b:'2'
}
}
},
//子组件载入前合并一次
mounted(){
Object.assign( this.form,this.value)
},
//父组件value值发生变化时子组件监听到合并一次
watch: {
value:{
handler(newVal, oldVal) {
console.log(newVal);
Object.assign( this.form,this.value)
},
immediate: true,
deep: true,
},
},
Object.assign用法:
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。
注意,如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性。