Vue responsive characteristics
1. When you use an object, you must first declare, this property is the type of response
2. to increase recursive object data getter and setter
3. The array set objects, responsive support an object changes, constant no effect
4. Modify the length of the array and index is updated does not result in view of
5. If you are new data (object type), vue will help you monitor
vue listen data may be an object, an array, or other basic value
1. First of all that the basic data
// 创建一个观察者函数
function observer(obj) {
// 判断obj如果不是对象 或者 是 null, 就直接返回
if (typeof obj !== "object" || typeof obj == null) {
return obj
}
// 判断数据是不是数组
if (Array.isArray(obj)) {
} else {
// 否则 就是对象
for (let key in obj) {
// 该函数只处理数据是对象的情况
defineReactive(obj, key, obj[key])
}
}
}
function defineReactive(obj, key, value) {
}
// 测试
let data = 10
console.log(observer(data)) // 10
Bin first step, followed by treatment of the object is determined is the case, the function is defineReactive
function defineReactive(obj, key, value) {
Object.defineProperty(obj, key, {
get() {
return value
},
set(newValue) {
if (value !== newValue) {
value = newValue
console.log("数据更新:" + newValue)
}
}
})
}
let data = {
age: 10
}
observer(data)
data.age = 30 // 数据更新:30
Next look at the function, but now modified data.age = 30, the value of this layer, if it is a multi-layer nested objects, will find no longer updated, such as below this
let data = {
age: {
id: 10
}
}
observer(data)
data.age.id = 20
The upper function, only the first layer of processed data, will add getter, setter, but after multiple nested, and does not increase the response of formula
let data = {
name: "李四",
age: {
id: 10
}
}
observer(data)
data.age.id = 20
data.name = "王参谋"
console.log(data)
But only updated once, so we need to recursive processing the data, that is, the new data may be modified objects, after traversing the first layer, its value may also be a target,
It is necessary to have a recursive call observer in two places () function
After the recursion
function defineReactive(obj, key, value) {
observer(value) // 递归处理函数
Object.defineProperty(obj, key, {
get() {
return value
},
set(newValue) {
if (value !== newValue) {
value = newValue
observer(value) // 递归函数
console.log("数据更新:" + newValue)
}
}
})
}
let data = {
name: "李四",
age: {
id: 10
}
}
observer(data)
data.age.id = 20
data.name = "王参谋"
console.log(data);
console.log(data.age);
It can be seen after the recursion, all objects are added to the setter and getter
Then processing If the value passed is an array ...