最近看了vue2.0源码关于响应式的实现,以下博文将通过简单的代码还原vue2.0关于响应式的实现思路。

注意,这里只是实现思路的还原,对于里面各种细节的实现,比如说数组里面数据的操作的监听,以及对象嵌套这些细节本实例都不会涉及到,如果想了解更加细节的实现,可以通过阅读源码 observer文件夹以及instance文件夹里面的state文件具体了解。

首先,我们先定义好实现vue对象的结构

class Vue {
constructor(options) {
this.$options = options;
this._data = options.data;
this.$el = document.querySelector(options.el);
}
}

第一步:将data下面的属性变为observable

使用Object.defineProperty对数据对象做属性get和set的监听,当有数据读取和赋值操作时则调用节点的指令,这样使用最通用的=等号赋值就可以触发了。

//数据劫持,监控数据变化
function observer(value, cb){
Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
} function defineReactive(obj, key, val, cb) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
return val
},
set: newVal => {
if(newVal === val)
return
val = newVal
}
})
}

第二步:实现一个消息订阅器

很简单,我们维护一个数组,这个数组,就放订阅者,一旦触发notify,订阅者就调用自己

的update方法

class Dep {
constructor() {
this.subs = []
}
add(watcher) {
this.subs.push(watcher)
}
notify() {
this.subs.forEach((watcher) => watcher.cb())
}
}

每次set函数,调用的时候,我们触发notify,实现更新

那么问题来了。谁是订阅者。对,是Watcher。。一旦 dep.notify()就遍历订阅者,也就是Watcher,并调用他的update()方法

function defineReactive(obj, key, val, cb) {
const dep = new Dep()
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
return val
},
set: newVal => {
if(newVal === val)
return
val = newVal
dep.notify()
}
})
}

第三步:实现一个 Watcher

Watcher的实现比较简单,其实就是执行数据变化时我们要执行的操作

class Watcher {
constructor(vm, cb) {
this.cb = cb
this.vm = vm
}
update(){
this.run()
}
run(){
this.cb.call(this.vm)
}
}

第四步:touch拿到依赖

上述三步,我们实现了数据改变可以触发更新,现在问题是我们无法将watcher与我们的数据联系到一起。

我们知道data上的属性设置defineReactive后,修改data 上的值会触发 set。那么我们取data上值是会触发 get了。所以可以利用这一点,先执行以下render函数,就可以知道视图的更新需要哪些数据的支持,并把它记录为数据的订阅者。

function defineReactive(obj, key, val, cb) {
const dep = new Dep()
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
if(Dep.target){
dep.add(Dep.target)
}
return val
},
set: newVal => {
if(newVal === val)
return
val = newVal
dep.notify()
}
})
}

最后我们来看用一个代理实现将我们对data的数据访问绑定在vue对象上

 _proxy(key) {
const self = this
Object.defineProperty(self, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return self._data[key]
},
set: function proxySetter (val) {
self._data[key] = val
}
})
} Object.keys(options.data).forEach(key => this._proxy(key))

下面就是整个实例的完整代码

class Vue {
constructor(options) {
this.$options = options;
this._data = options.data;
this.$el =document.querySelector(options.el);
Object.keys(options.data).forEach(key => this._proxy(key))
observer(options.data)
watch(this, this._render.bind(this), this._update.bind(this))
}
_proxy(key) {
const self = this
Object.defineProperty(self, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return self._data[key]
},
set: function proxySetter (val) {
self._data[key] = val
}
})
}
_update() {
console.log("我需要更新");
this._render.call(this)
}
_render() {
this._bindText();
} _bindText() {
let textDOMs=this.$el.querySelectorAll('[v-text]'),
bindText;
for(let i=0;i<textDOMs.length;i++){
bindText=textDOMs[i].getAttribute('v-text');
let data = this._data[bindText];
if(data){
textDOMs[i].innerHTML=data;
}
}
}
} function observer(value, cb){
Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
} function defineReactive(obj, key, val, cb) {
const dep = new Dep()
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
if(Dep.target){
dep.add(Dep.target)
}
return val
},
set: newVal => {
if(newVal === val)
return
val = newVal
dep.notify()
}
})
}
function watch(vm, exp, cb){
Dep.target = new Watcher(vm,cb);
return exp()
} class Watcher {
constructor(vm, cb) {
this.cb = cb
this.vm = vm
}
update(){
this.run()
}
run(){
this.cb.call(this.vm)
}
} class Dep {
constructor() {
this.subs = []
}
add(watcher) {
this.subs.push(watcher)
}
notify() {
this.subs.forEach((watcher) => watcher.cb())
}
}
Dep.target = null;

var demo = new Vue({
el: '#demo',
data: {
text: "hello world"
}
})


setTimeout(function(){
demo.text = "hello new world"


}, 1000)

  <body>
<div id="demo">
<div v-text="text"></div>
</div>
</body>

上面就是整个vue数据驱动部分的整个思路。如果想深入了解更细节的实现,建议深入去看vue这部分的代码。

实现vue2.0响应式的基本思路的更多相关文章

  1. Vue2.0响应式原理以及重写数组方法

    // 重写数组方法 let oldArrayPrototype = Array.prototype; let proto = Object.create(oldArrayPrototype); ['p ...

  2. vue2.0与3.0响应式原理机制

    vue2.0响应式原理 - defineProperty 这个原理老生常谈了,就是拦截对象,给对象的属性增加set 和 get方法,因为核心是defineProperty所以还需要对数组的方法进行拦截 ...

  3. Vue3.0工程创建 && setup、ref、reactive函数 && Vue3.0响应式实现原理

    1 # 一.创建Vue3.0工程 2 # 1.使用vue-cli创建 3 # 官方文档: https://cli.vuejs.org/zh/guide/creating-a-project.html# ...

  4. 【SpringBoot】SpringBoot2.0响应式编程

    ========================15.高级篇幅之SpringBoot2.0响应式编程 ================================ 1.SprinBoot2.x响应 ...

  5. Vue 2.0 与 Vue 3.0 响应式原理比较

    Vue 2.0 的响应式是基于Object.defineProperty实现的 当你把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的 prop ...

  6. 【js】vue 2.5.1 源码学习 (七) 初始化之 initState 响应式系统基本思路

    大体思路(六) 本节内容: 一.生命周期的钩子函数的实现 ==> callHook(vm , 'beforeCreate') beforeCreate 实例创建之后 事件数据还未创建 二.初始化 ...

  7. Vue2.0流式渲染中文乱码问题

    在参照vue2.0中文官方文档学习服务端渲染之流式渲染时,因为响应头默认编码类型为GBK,而文件为UFT-8类型,所以出现了中文乱码问题. 解决办法:设置响应头编码类型即可 response.setH ...

  8. Vue3.0 响应式数据原理:ES6 Proxy

    Vue3.0 开始用 Proxy 代替 Object.defineProperty了,这篇文章结合实例教你如何使用Proxy 本篇文章同时收录[前端知识点]中,链接直达 阅读本文您将收获 JavaSc ...

  9. Vue2.x响应式原理

    一.回顾Vue响应式用法 ​ vue响应式,我们都很熟悉了.当我们修改vue中data对象中的属性时,页面中引用该属性的地方就会发生相应的改变.避免了我们再去操作dom,进行数据绑定. 二.Vue响应 ...

随机推荐

  1. 巧用Alt 键

    1,查看表的元数据信息 在TSQL 查询编辑器中,选中一个表,如图 点击Alt+F1,就可以查看表的元数据,列的定义和ID列等 2,使用Alt批量插入逗号 在TQL语句中,有时为了使用 in 子句,必 ...

  2. 【Orleans开胃菜系列1】不要被表象迷惑

    [Orleans开胃菜系列1]不要被表象迷惑 /** * prism.js Github theme based on GitHub's theme. * @author Sam Clarke */ ...

  3. Inno Setup脚本

    某天夜晚一场狂风暴雨,由于办公室座位旁的窗户没关,笔记本电脑泡了一夜水,无法开机,无奈送修,里面的大量资料也不知道会不会丢失. is的脚本只有重新写了,重新研究了一下检测程序是否正在运行的判断方法,另 ...

  4. VMware下三种网络连接模式介绍

    birdged(桥接) 桥接网络是指本地物理网卡和虚拟网卡通过VMnet0虚拟交换机进行桥接,物理网卡和虚拟网卡在拓扑图上处于同等地位,那么物理网卡和虚拟网卡就相当于处于同一个网段,虚拟交换机就相当于 ...

  5. (转)Unity内建图标列表

    用法 Gizmos.DrawIcon(transform.position, "PointLight Gizmo"); UnityEditor.EditorGUIUtility.F ...

  6. 微软职位内部推荐-Senior Software Engineer - Back End

    微软近期Open的职位: SharePoint is a multi-billion dollar enterprise business that has grown from an on-prem ...

  7. 5分钟让你明白HTTP协议

    一.HTTP简介 1.http协议介绍 HTTP协议(HyperText Transfer Protocol,超文本传输协议)是因特网上应用最为广泛的一种网络传输协议,所有的WWW文件都必须遵守这个标 ...

  8. .net中操作Visual SourceSafe

    最近整理一些资料,发现以前写的一段代码,提供对微软的版本管理软件visual sourcesafe的一些操作.以下简称vss. 想起以前写的时候,因为资料比较匮乏,只能边研究边测试,走了不少弯路. 由 ...

  9. classpath与clsspath*

    classpath是指 WEB-INF文件夹下的classes目录 classes含义: 1.存放各种资源配置文件 eg.init.properties log4j.properties struts ...

  10. Hadoop 5 Hbase 遇到的问题

    hbase伪分布式配置完成后: 在bin/hbase shell 进行create操作时出现:Can't get master address from ZooKeeper; znode data = ...