关于Vue监听不到Array响应变化以及响应式原理剖析的一个问题
哈喽,大家好,我是小朱,一位即将步入大学的前端小菜鸟,这是我的第一篇文章,望大家多多包涵。 那么这篇文章我要聊的一个问题就是《Vue2中监听不到数组响应的问题》。
提出问题
不知道大家在使用Vue的时候有没有遇到这样一个问题,假设data里面声明了一个数组,当你修改数据试图来触发view更新的时候,你会发现数据变了,但是视图没有变的情况,往下看
复现问题
首先这是我定义的数据
data() {
return {
list: [{ a: 1 }, "我是原始数据"],
};
},
mounted() {
//这里定义了一个定时器2秒之后触发更新
setTimeout(() => {
this.list[0].a = 2;
this.list[1] = "我改变了";
}, 2000);
}
这是渲染的view
两秒之后view更新了
我们发现没问题哈,确实没问题,您继续往下看
setTimeout(() => {
this.list[1] = "我改变了";
}, 2000);
我们只更新一个基本类型的数据
这时你会发现数据改变了,但是view没有更新
解决方案
Vue官方给出的一个api,可以让我们手动触发更新
setTimeout(() => {
this.$set(this.list, 1, "我被修改了");
}, 2000);
可以看到值已经被修改了,而且现在你再去更改的话他也是可以触发更新的, 那么这个时候引人深思,他为什么是这样的呢,为什么Vue监测不到数据被更改了,您接着往下看
原理剖析
这里我们要介绍一个Js的Api,Object.defineProperty()
Object.defineProperty方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。( 这是MDN介绍 ) Link
使用方式
Object.defineProperty(obj, prop, descriptor)
可以看到这个Api是针对于对象使用的,那么现在我们展示源码
line :163 path: core/observer/index.js
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
这是在Vue中对data负责定义响应的方法,那么在前面还有一个重要的函数 Observer
line :37 path: core/observer/index.js
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
// 如果是数组
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
这个是Vue响应式原理的一个Observer
对象,它主要的作用是对传过来的data进行判断选择定义方式的一个对象 ,可以看到 1. 如果数据是一个非数组的key的时候他会调用 walk
这个方法,它的职责主要对key进行一个遍历来定义响应式,当然data可能存在嵌套的结构,Vue中也是做了递归处理的 2. 如果数据是一个数组的key的时候他会调用 对应的数组处理的方法
那么会看到处理数组的时候,他传了一个 arrayMethods
这个方法,咱们接着往下看
arrayMethods
line :9 path: core/observer/array.js
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator (...args) {
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
arrayMethods 这个方法,他是对原生Js的一些可以修改数组的方法进行了一个重写,所以当数组触发这些方法的时候,会触发Vue的响应式更新,会触发view的更新
总结
Vue 通过 Object.defineProperty
这个Api来进行对对象的响应式监听,对数组通过重写数组方法的方式来进行监听,而我们直接使用 arr[0] = 123
这种的索引方式来进行修改的时候他是监听不到了,那么我们需要使用Vue.set()这个方法来解决这个问题,当然这也是Vue2中才会出现的问题,Vue3中采用了 Proxy 的方式重写了响应式定义,也就不存在这个问题了,也提高了相应的性能。
好啦,这篇文章也是到了结尾,希望我的付出可以换来大家的支持,本人前端小菜鸟,大佬勿喷,嘿嘿。