来自拉勾教育大前端训练营 vue框架源码与进阶模块,以下内容为个人在学习过程中对响应式原理的总结~
先实现mini 版Vue之前,我们先来了解一些概念
数据驱动
数据响应式、双向绑定、数据驱动
数据响应式
数据模型仅仅是普通对象的JavaScript,而我们修改数据时,视图会进行更新,避免了繁琐的DOM操作,提高开发效率
双向绑定
数据改变,视图改变,数据也随之改变
我们可以使用v-model在表单元素上创建双向数据绑定
数据驱动是Vue最独特的特性之一
let data = {
msg: '大白菜'
}
// 模拟Vue的实例
let vm = {}
// 数据劫持, 当访问或者设置vm中成员的时候,做一些干预操作
Object.defineProperty(vm, 'msg', {
// 可枚举
enumerable: true,
// 可配置 (可以使用delete杉树,也可通过defineProperty重新定义)
configurable: true,
get () {
return data.msg
},
set (newValue) {
if (newValue === data.msg) {
return
}
data.msg = newValue
// 数据更改,更新DOM的值
document.querySelector("#app").textContent = data.msg
}
})
// 测试
vm.msg = 'Hello word'
console.log(vm.msg)
// 多个属性
let vm = {}
proxyData(data)
function proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(vm, key, {
enumerable: true,
configurable: true,
get () {
console.log('set:', key, data[key])
return data[key]
},
set(newValue) {
if (newValue === data[key]) {
return
}
data[key] = newValue
document.querySelector("#app").textContent = data[key]
}
})
})
}
// vm.msg = '大白菜'
// set: msg 大白菜
let data = {
msg: 'hello'
}
let vm = new Proxy(data, {
get(target, key) {
return target[key]
},
// 设置vm的成员会执行
set(target, key, newValue) {
console.log('set', key, newValue)
if (target[key] === newValue) {
return
}
target[key] = newValue
document.querySelector('#app').textContent = target[key]
}
})
vm.msg = '大白菜'
console.log(vm.msg)
我们假定,存在一个“信号中心”,某个任务执行完成,就向信号中心“发布” (publish)一个信号,其他任务可以向信号中心“订阅” (subscribe)这个信号,从而知道什么时候自己可以开始执行,这就叫做“发布/定于模式” (publish-subscribe pattern)
let vm = new Vue()
// 注册事件(订阅消息)
vm.$on('dataChange', () => {
console.log('dataChange')
})
vm.$on('dataChange', () => {
console.log('dataChange1')
})
// 触发事件(发布消息)
// 自定义事件
class EventEmitter {
constructor () {
this.subs = Object.create(null)
}
// 注册事件
$on (eventType, handler) {
this.subs[eventType] = this.subs[eventType] || []
this.subs[eventType].push(handler)
}
// 触发事件
$emit (eventType) {
if (this.subs[eventType]) {
this.subs[eventType].forEach(handler => {
handler()
})
}
}
}
// 测试一下
let em = new EventEmitter()
em.$on('click', () => {
console.log('click1')
})
em.$on('click', function() {
console.log('click2')
})
em.$emit('click')
class Dep {
constructor () {
// 记录所有的订阅者
this.subs = []
}
// 添加观察者
addSub() {
if (sub && sub.update) {
this.subs.push(sub)
}
}
notify () {
this.subs.forEach(sub => {
sub.update()
})
}
}
class Watcher {
update () {
console.log('update')
}
}
// 测试一下
let dep = new Dep()
let watcher = new Watcher()
dep.addSub(watcher)
dep.notify()
好啦,说这么多,终于到了如何去实现mini版vue了,下面我们将一步一步去实现mini版的vue
结构
+ $options
+ $el
+ $data
+ _proxyData
首先在文件中新增一个vue.js文件
class Vue {
constructor (options) {
// 1. 通过属性保存选项的数据
// 2. 把data中的成员转换成getter和setter,注入到Vue实例中
// 3. 调用observer对象,监听数据的辩护
// 4. 调用compiler对象, 解析指令和差值表达式
}
// 代理数据
_proxyData (data) {
}
}
完整代码
// vue.js
class Vue {
constructor (options) {
// 1. 通过属性保存选项的数据
this.$options = options || {}
this.$data = options.data || {}
this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el
// 2. 把data中的成员转换成getter和setter,注入到Vue实例中
this._proxyData(this.$data)
// 3. 调用observer对象,监听数据的辩护
new Observer(this.$data)
// 4. 调用compiler对象, 解析指令和差值表达式
}
_proxyData (data) {
// 遍历data中的所有属性
Object.keys(data).forEach(key => {
// 把data的属性注入到Vue实例中
Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
get () {
return data[key]
},
set(newValue) {
if (newValue === data[key]) {
return
}
data[key] = newValue
}
})
})
}
}
// 测试一下
// 控制台输入vm看是有实例
这个时候我们需要在index.html去使用Vue.js
<script src="vue.js"></script>
let vm = new Vue({
el: '#app',
data: {
msg: 'Hello Vue',
count: 100
},
})
console.log(vm.msg)
+ walk(data)
+ defineReactive(data, key, value)
新建一个observer.js
, 在index.html
中引入
// +walk(data)
// + defineReactive(data, key, value)
// 结构
class Observer {
walk (data) {
}
defineReactive (obj, key, val) {
}
}
完成代码
class Observer {
constructor (data) {
this.walk(data)
}
walk (data) {
// 1. 判断data是否是对象
if (!data || typeof data !== 'object') {
return
}
// 2. 遍历data对象的所有属性
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
defineReactive (obj, key, val) {
let that = this
// 如果val是对象,把val内部的属性转换成响应式数据
this.walk(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get () {
return val
},
set (newValue) {
if (newValue === val) {
return
}
val = newValue
that.walk(newValue)
//发送通知
}
})
}
}
测试一下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
</head>
<body>
<div id="app">
<h1>大白菜</h1>
<h1>{{ msg }}</h1>
<h1>{{ count }}</h1>
<div>{{ name }}</div>
<h1>v-text</h1>
<div v-html="htmlStr"></div>
<div v-text="msg"></div>
<input type="text" v-model="msg">
<input type="text" v-model="count">
</div>
<script src="observer.js"></script>
<script src="vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'Hello Vue',
count: 100,
person: {
name: 'zzzz'
}
}
})
console.log(vm.msg)
vm.msg = { test: '大白菜~' }
</script>
</body>
</html>
记得在vue.js
第三步 调用Observer
new Observer(this.$data)
Compiler功能
Compiler结构
+ el
+ vm
+ compile(el)
+ compileElement(node)
+ compileText(node)
+ isDirective(arrrNode)
+ isTextNode(node)
+ isElementNode(node)
新建compiler.js
// 接下来会一步一步实现这个compiler.js的方法
class Compiler {
constructor (vm) {
this.el = vm.$el
this.vm = vm
}
// 编译模板, 处理文本节点和元素节点
compile (el) {
}
// 编译元素节点, 出来指令
compileElement (node) {
}
// 编译文本节点,出来插值表达式
compileText (node) {
}
// 判断元素属性是否是指令
isDirective(attrName) {
return attrName.startsWith('v-')
}
// 判断节点是否是文本节点
isTextNode (node) {
return node.nodeType === 3
}
// 判读节点是否是元素节点
isElementNode (node) {
return node.nodeType === 1
}
}
class Compiler {
constructor (vm) {
this.el = vm.$el
this.vm = vm
this.compile(this.el)
}
// 编译模板, 处理文本节点和元素节点
compile (el) {
let childNodes = el.childNodes
Array.from(childNodes).forEach(node => {
// 处理文本节点
if (this.isTextNode(node)) {
this.compileText(node)
} else if (this.isElementNode(node)) {
// 处理元素节点
this.compileElement(node)
}
// 判断node节点,是否有子节点, 如果有子节点,要递归调用compile
if (node.childNodes && node.childNodes.length) {
this.compile(node)
}
})
}
}
// 编译文本节点,出来差值
compileText (node) {
// console.dir(node)
let reg = /\{\{(.+?)\}\}/
let value = node.textContent
if (reg.test(value)) {
let key = RegExp.$1.trim()
node.textContent = value.replace(reg, this.vm[key])
}
}
// 编译元素节点, 出来指令
compileElement (node) {
console.log(node.attributes)
// 遍历所有的属性节点
Array.from(node.attributes).forEach(attr => {
// 判断是否是指令
let attrName = attr.name
if (this.isDirective(attrName)) {
// v-text --> text
attrName = attrName.substr(2)
let key = attr.value
this.update(node, key, attrName)
}
})
}
update (node, key, attrName) {
let updateFn = this[attrName + 'Updater']
updateFn && updateFn(node, this.vm[key])
}
看图
功能
Dep结构
+ subs
+ addSubs(sub)
+ notify
新建Dep.js
class Dep {
constructor () {
// 存储所有的观察者
this.subs = []
}
// 添加观察者
addSub (sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
// 发送通知
notify () {
this.subs.forEach(sub => {
sub.update()
})
}
}
完成dep.js
之后,我们需要在Observer.js
中的defineReactive
中创建Dep
对象
defineReactive (obj, key, val) {
let that = this
// 负责收集依赖, 并发送通知
let dep = new Dep()
// 如果是val对象,把val内部的属性转换成响应式对象
that.walk(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get () {
// 收集依赖
Dep.target && dep.addSub(Dep.target)
return val
},
set (newValue) {
if (newValue === val) {
return
}
val = newValue
that.walk(newValue)
// 发送通知
dep.notify()
}
})
}
Watcher
+ vm
+ key
+ cb
+ oldValue
+ update
新建watcher.js
文件
class Watcher {
constructor (vm, key, cb) {
this.vm = vm;
// data中的属性名称
this.key = key;
// 回调函数负责更新视图
this.cb = cb;
// 把Watcher对象变化的时候更新视图
Dep.target = this;
// 触发get方法, 在get方法中调用addSub
this.oldValue = vm[key];
Dep.target = null
}
// 当数据发生变化的时候更新视图
update () {
let newValue = this.vm[this.key];
// 判断新值和旧值是否相等
if (this.oldValue === newValue) {
return
}
this.cb(newValue)
}
}
我们需要在compile.js
中的 compileText
、textUpdater
、modelUpdater
去创建watcher对象
// 编译文本节点,出来差值
compileText (node) {
// console.dir(node)
let reg = /\{\{(.+?)\}\}/
let value = node.textContent
if (reg.test(value)) {
let key = RegExp.$1.trim()
node.textContent = value.replace(reg, this.vm[key])
// 创建watcher对象, 当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
}
// 处理 v-text 指令
textUpdater (node, value, key) {
node.textContent = value
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
// v-model
modelUpdater (node, value, key) {
node.value = value;
new Watcher(this.vm, key, (newValue) => {
node.value = newValue
})
}
// 传入key
update (node, key, attrName) {
let updateFn = this[attrName + 'Updater']
updateFn && updateFn.call(this, node, this.vm[key], key)
}
此时在vue.js第四步中调用compile对象,解析指令和插值表达式
// 4. 调用compiler对象, 解析指令和差值表达式
new Compiler(this)
打开控制台即可看到如下效果,到这里,mini版的vue就基本完成了
给input注册事件,实现双向绑定
// v-model
modelUpdater (node, value, key) {
node.value = value;
new Watcher(this.vm, key, (newValue) => {
node.value = newValue
})
// 双向绑定
node.addEventListener('input', () => {
this.vm[key] = node.value
})
}
完成代码已提交到github
请点击这里
最后感谢您花宝贵的时间阅读这篇内容,如果你觉得这篇内容对你有帮助的话,就给本文点个赞吧。
(感大家的的鼓励与支持)