实现vue2.0响应式的基本思路
最近看了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响应式的基本思路的更多相关文章
- Vue2.0响应式原理以及重写数组方法
// 重写数组方法 let oldArrayPrototype = Array.prototype; let proto = Object.create(oldArrayPrototype); ['p ...
- vue2.0与3.0响应式原理机制
vue2.0响应式原理 - defineProperty 这个原理老生常谈了,就是拦截对象,给对象的属性增加set 和 get方法,因为核心是defineProperty所以还需要对数组的方法进行拦截 ...
- 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# ...
- 【SpringBoot】SpringBoot2.0响应式编程
========================15.高级篇幅之SpringBoot2.0响应式编程 ================================ 1.SprinBoot2.x响应 ...
- Vue 2.0 与 Vue 3.0 响应式原理比较
Vue 2.0 的响应式是基于Object.defineProperty实现的 当你把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的 prop ...
- 【js】vue 2.5.1 源码学习 (七) 初始化之 initState 响应式系统基本思路
大体思路(六) 本节内容: 一.生命周期的钩子函数的实现 ==> callHook(vm , 'beforeCreate') beforeCreate 实例创建之后 事件数据还未创建 二.初始化 ...
- Vue2.0流式渲染中文乱码问题
在参照vue2.0中文官方文档学习服务端渲染之流式渲染时,因为响应头默认编码类型为GBK,而文件为UFT-8类型,所以出现了中文乱码问题. 解决办法:设置响应头编码类型即可 response.setH ...
- Vue3.0 响应式数据原理:ES6 Proxy
Vue3.0 开始用 Proxy 代替 Object.defineProperty了,这篇文章结合实例教你如何使用Proxy 本篇文章同时收录[前端知识点]中,链接直达 阅读本文您将收获 JavaSc ...
- Vue2.x响应式原理
一.回顾Vue响应式用法 vue响应式,我们都很熟悉了.当我们修改vue中data对象中的属性时,页面中引用该属性的地方就会发生相应的改变.避免了我们再去操作dom,进行数据绑定. 二.Vue响应 ...
随机推荐
- 架构师修练 I - 超级代码控
可实现的是架构,空谈是概念 So don't tell me the concepts show me the code! “不懂编码的架构师不是好架构师” 好架构师都是超级代码控. 代码是最好 ...
- Error when Building GPU docker image for caffe: Unsupported gpu architecture 'compute_60'
issue: Error when Building GPU docker image for caffe: Unsupported gpu architecture 'compute_60' rea ...
- node基础:文件系统-文件读取
node的文件读取主要分为同步读取.异步读取,常用API有fs.readFile.fs.readFileSync.还有诸如更底层的fs.read,以及数据流(stream),后面再总结下咯~ 直接上简 ...
- Windows中的键盘快捷方式
Windows 中的键盘快捷方式 适用于: Windows 10Windows 8.1Windows 7 Windows 10 键盘快捷方式就是按键或按键组合,可提供一种替代方式来执行通常使用鼠标执行 ...
- L2-031 深入虎穴(BFS)
著名的王牌间谍 007 需要执行一次任务,获取敌方的机密情报.已知情报藏在一个地下迷宫里,迷宫只有一个入口,里面有很多条通路,每条路通向一扇门.每一扇门背后或者是一个房间,或者又有很多条路,同样是每条 ...
- 第三周 构造一个简单的Linux系统MenuOS
一. Linux内核源代码简介 稳定版内核:Linux-3.18.6 Linux内核源代码的目录结构: arch目录:在Linux内核源代码里占有的比重很大,因为Linux内核支持很多的体系结构, ...
- Linux命令(十九) 查看系统负载 uptime
一.命令介绍 Linux 系统中 uptime 命令主要用于获取主机运行时长和查询Linux系统负载等信息. uptime 命令可以显示系统已经运行了多长时间,信息显示依次为:现在时间.系统已经运行时 ...
- Oracle 导入单表数据
1. 测试一下 删除某一张表,然后 通过 expdp 数据库泵的备份来恢复数据. 测试过程 ) from bizlog COUNT() ---------- 151 drop table bizlog ...
- 消息队列1:RabbitMQ解析并基于Springboot实战
RabbitMQ简介 AMQP:Advanced Message Queue,高级消息队列协议.它是应用层协议的一个开放标准,为面向消息的中间件设计,基于此协议的客户端与消息中间件可传递消息,并不受产 ...
- 【刷题】BZOJ 2151 种树
Description A城市有一个巨大的圆形广场,为了绿化环境和净化空气,市政府决定沿圆形广场外圈种一圈树.园林部门得到指令后,初步规划出n个种树的位置,顺时针编号1到n.并且每个位置都有一个美观度 ...