4.3.4,舌下腺囊肿症状,迅雷vip账号
介绍
observer是vue核心中最重要的一个模块(个人认为),能够实现视图与数据的响应式更新,底层全凭observer的支持。
注意:本文是针对vue@2.1.8进行分析
observer模块在vue项目中的代码位置是src/core/observer,模块共分为这几个部分:
示意图如下:
observer
observer类定义在src/core/observer/index.js中,先来看一下observer的构造函数
constructor (value: any) { this.value = value this.dep = new dep() this.vmcount = 0 def(value, '__ob__', this) if (array.isarray(value)) { const augment = hasproto ? protoaugment : copyaugment augment(value, arraymethods, arraykeys) this.observearray(value) } else { this.walk(value) } }
value是需要被观察的数据对象,在构造函数中,会给value增加__ob__属性,作为数据已经被observer观察的标志。如果value是数组,就使用observearray遍历value,对value中每一个元素调用observe分别进行观察。如果value是对象,则使用walk遍历value上每个key,对每个key调用definereactive来获得该key的set/get控制权。
解释下上面用到的几个函数的功能:
如果不太理解上面的文字描述可以看一下图:
dep
dep是observer与watcher之间的纽带,也可以认为dep是服务于observer的订阅系统。watcher订阅某个observer的dep,当observer观察的数据发生变化时,通过dep通知各个已经订阅的watcher。
dep提供了几个接口:
watcher
watcher是用来订阅数据的变化的并执行相应操作(例如更新视图)的。watcher的构造器函数定义如下:
constructor (vm, exporfn, cb, options) { this.vm = vm vm._watchers.push(this) // options if (options) { this.deep = !!options.deep this.user = !!options.user this.lazy = !!options.lazy this.sync = !!options.sync } else { this.deep = this.user = this.lazy = this.sync = false } this.cb = cb this.id = ++uid // uid for batching this.active = true this.dirty = this.lazy // for lazy watchers this.deps = [] this.newdeps = [] this.depids = new set() this.newdepids = new set() this.expression = process.env.node_env !== 'production' ? exporfn.tostring() : '' if (typeof exporfn === 'function') { this.getter = exporfn } else { this.getter = parsepath(exporfn) if (!this.getter) { this.getter = function () {} process.env.node_env !== 'production' && warn( `failed watching path: "${exporfn}" ` + 'watcher only accepts simple dot-delimited paths. ' + 'for full control, use a function instead.', vm ) } } this.value = this.lazy ? undefined : this.get() }
参数中,vm表示组件实例,exporfn表示要订阅的数据字段(字符串表示,例如a.b.c)或是一个要执行的函数,cb表示watcher运行后的回调函数,options是选项对象,包含deep、user、lazy等配置。
watcher实例上有这些方法:
array methods
在src/core/observer/array.js中,vue框架对数组的push、pop、shift、unshift、sort、splice、reverse方法进行了改造,在调用数组的这些方法时,自动触发dep.notify(),解决了调用这些函数改变数组后无法触发更新的问题。
在vue的官方文档中对这个也有说明:http://cn.vuejs.org/v2/guide/list.html#变异方法
总结
以上就是这篇文中的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
VUE+elementui组件在table-cell单元格中绘制微型echarts图
Vue通过getAction的finally来最大程度避免影响主数据呈现问题
vue 路由懒加载中给 Webpack Chunks 命名的方法
网友评论