1. Vue.set的使用
Vue.set的作用:向响应式对象中添加一个属性,并让其也变成响应式的
2. Vue.set的源码
function set (target, key, val) {
if (isUndef(target) || isPrimitive(target)
) {
warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
- 判断若target为基础数据类型,抛出警告
if (isUndef(target) || isPrimitive(target)
) {
warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
}
- 如果target为数组且key为有效的数组key时,将数组的长度设置为target.length和key中的最大的那一个,然后调用数组的splice方法(vue中重写的splice方法)添加元素;
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
- 如果target对象上已经存在key,且这个key不是Object原型对象上的属性。这说明key这个属性已经是响应式的了,那么就则直接将val赋值给这个属性
if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
- 判断当target为vue实例或根数据data对象时,在开发环境下抛错
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
-
当一个数据为响应式时,vue会给该数据添加一个__ob__属性;
当target是非响应式数据时, 我们就按照普通对象添加属性的方式来处理;
let obj ={} this.$set(obj,'name','张三') // 此时obj非响应式数据当target对象是响应式数据时,我们将target的属性key也设置为响应式并手动触发通知其属性值的更新;
ob.value其实就是target,只不过它是Vue实例上$data里的已经被追踪依赖的对象。
var ob = (target).__ob__; ... if (!ob) {//非响应式数据 target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify();