MCPcopy
hub / github.com/ygs-code/vue / set

Function set

vue.js:1572–1615  ·  view source on GitHub ↗
(target, key, val)

Source from the content-addressed store, hash-verified

1570 //如果是对象则重新赋值
1571 //如果 (target).__ob__ 存在则表明该数据以前添加过观察者对象中 //通知订阅者ob.value更新数据 添加观察者 define set get 方法
1572 function set(target, key, val) {
1573 if ("development" !== 'production' &&
1574 //判断数据 是否是undefined或者null
1575 (isUndef(target) || isPrimitive(target)) //判断数据类型是否是string,number,symbol,boolean
1576 ) {
1577 //必须是对象数组才可以 否则发出警告
1578 warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
1579 }
1580
1581 //如果是数组 并且key是数字
1582 if (Array.isArray(target) && isValidArrayIndex(key)) {
1583 //设置数组的长度
1584 target.length = Math.max(target.length, key);
1585 //像数组尾部添加一个新数据,相当于push
1586 target.splice(key, 1, val);
1587 return val
1588 }
1589 //判断key是否在target 上,并且不是在Object.prototype 原型上,而不是通过父层原型链查找的
1590 if (key in target && !(key in Object.prototype)) {
1591 target[key] = val; //赋值
1592 return val
1593 }
1594 var ob = (target).__ob__; //声明一个对象ob 值为该target对象中的原型上面的所有方法和属性 ,表明该数据加入过观察者中
1595 //vmCount 记录vue被实例化的次数
1596 //是不是vue
1597 if (target._isVue || (ob && ob.vmCount)) {
1598 //如果不是生产环境,发出警告
1599 "development" !== 'production' && warn(
1600 'Avoid adding reactive properties to a Vue instance or its root $data ' +
1601 'at runtime - declare it upfront in the data option.'
1602 );
1603 return val
1604 }
1605 //如果ob不存在 说明他没有添加观察者 则直接赋值
1606 if (!ob) {
1607 target[key] = val;
1608 return val
1609 }
1610 //通知订阅者ob.value更新数据 添加观察者 define set get 方法
1611 defineReactive(ob.value, key, val);
1612 //通知订阅者ob.value更新数据
1613 ob.dep.notify();
1614 return val
1615 }
1616
1617 /**
1618 * Delete a property and trigger change if necessary.

Callers 1

mergeDataFunction · 0.85

Calls 4

isUndefFunction · 0.85
isPrimitiveFunction · 0.85
isValidArrayIndexFunction · 0.85
defineReactiveFunction · 0.85

Tested by

no test coverage detected