vue 组件响应式更新原理 All In One_Object.assign vue 组件响应式更新原理 All In One



vue 组件响应式更新原理 All In One

vue 组件更新原理 / vue 组件响应式原理

  1. 依赖收集
  2. 监听,通知
  3. 重绘

vue 组件响应式更新原理 All In One_Object.assign

对象​

var vm = new Vue({
data: {
a: 1
}
});
// `vm.a` 是响应式的

vm.b = 2;
// `vm.b` 是非响应式的

// Vue.set(vm.someObject, 'b', 2)

this.$set(this.someObject, "b", 2);

this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 });


数组​

var vm = new Vue({
data: {
items: ["a", "b", "c"]
}
});
vm.items[1] = "x"; // 不是响应性的
vm.items.length = 2; // 不是响应性的

// Vue.set
Vue.set(vm.items, indexOfItem, newValue);
vm.$set(vm.items, indexOfItem, newValue);

// Array.prototype.splice 就地复用
vm.items.splice(indexOfItem, 1, newValue);

vm.items.splice(newLength);


demo

  methods: {
// 1. 通过调用父组件的方法,更改 props ✅
updateForm(obj = {}, index = 0) {
// this.formData.creativeList[index] = obj;
// console.log("update data", obj, index);
if (!this.formData.creativeList[index]) {
this.formData.creativeList[index] = {};
} else {
// ✅对象属性合并
obj = Object.assign({}, this.formData.creativeList[index], obj);
// obj = {
// ...this.formData.creativeList[index],
// ...obj,
// };
}
// ❌ 非响应式,数组
// Object.assign(this.formData.creativeList[index], obj);
// ✅ 响应式,数组, this.$set
// this.$set(this.formData.creativeList, index, obj);
// ✅ 响应式,数组,Array.splice 就地复用
this.formData.creativeList.splice(
this.formData.creativeList[index],
1,
obj
);
},
// 2. 通过 Array[0].Object 对象引用,直接修改 props 的 formData 属性? 不推荐 ❌
},