vue Vue.set

2018-08-06  本文已影响0人  余带盐

在对象上设置一个属性。如果属性还不存在,则添加新属性并触发更改通知。

isUndef(target)
isPrimitive(target)
isValidArrayIndex(key)
target.splice(key, 1, val)
key in Object.prototype

/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
 if ("development" !== 'production' &&
   (isUndef(target) || isPrimitive(target))
 ) {//如果 target 是未定义或非对象
   warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
 }
 if (Array.isArray(target) && isValidArrayIndex(key)) {//验证 target是否是数组且key是否是有效正整数
   target.length = Math.max(target.length, key);//数组的长度取原数组长度和key的较大值
   target.splice(key, 1, val);//意思是删除数组中key序号处的一个元素,并添加val到key序号处,既包含了替换值,也包含了新增值
   return val
 }
 if (key in target && !(key in Object.prototype)) {//如果key在对象target中,且不在target的原型链中,说明这是替换值
   target[key] = val;
   return val
 }
//从这儿开始应该是新增对象的值,后面的以后解读
 var ob = (target).__ob__;
 if (target._isVue || (ob && ob.vmCount)) {
   "development" !== 'production' && 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(ob.value, key, val);
 ob.dep.notify();
 return val
}
上一篇 下一篇

猜你喜欢

热点阅读