Object.assign()
基本语法:
Object.assign(target,…source)
基本概念:
Object.assign(目标对象,…一个或者多个源对象)方法可以用来将源对象(source)中所有可枚举(枚举:就是可以遍历出来,不可枚举就是遍历不出来)的属性,复制到目标对象(target),也就是合并两个对象或多个对象给目标对象,注意:第一个参数一定是目标对象。
1.目标对象和源对象没有同名属性
🌰:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(result === target);
// expected output: true
如果只是想将两个或多个对象的属性合并到一起,不改变原有对象的属性,可以用一个空的对象作为target对象。像下面这样:
const result = Object.assign({}, target, source);
具体详情移步MDN
2.目标对象和源对象有同名属性
具体使用:在项目中一般会把新增和编辑在同一个弹窗中操作,而新打开弹窗时数据会有残留,这时可以用Object.assign()
方法。
this.$data // 当前data数据
this.$options.data() // 原始data数据
Object.assign(this.$data, this.$options.data())
可清空data中的数据
update(type, id) {
this.type = type
if (type === 'add') {
Object.assign(this.checkForm, this.$options.data().checkForm)
// this.checkForm 为当前表单数据,this.$options.data().checkForm 为data中checkForm的初始数据
var date = new Date()
this.checkForm.year = date.getFullYear() + ''
this.checkVisible = true
} else {
this.getDetail(id)
}
}