文件结构
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini Vue</title>
</head>
<body>
<div id="app">
<h1>差值表达式</h1>
<h3>{{msg}}</h3>
<h3>{{count}}</h3>
<h1>v-text</h1>
<div v-text="msg"></div>
<h1>v-model</h1>
<input type="text" v-model="msg">
<input type="text" v-model="count">
</div>
<script src="./js/dep.js"></script>
<script src="./js/watche.js"></script>
<script src="./js/compiler.js"></script>
<script src="./js/observer.js"></script>
<script src="./js/vue.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'Hello Vue',
count: 100,
person: { name: 'jax' }
}
});
</script>
</body>
</html>
vue.js
class Vue {
constructor(options) {
// 1. 通过属性保存选项的数据
this.$options = options || {}
this.$data = options.data || {}
const el = options.el
// options传入的el可能是字符串的形式,如果是字符串就是一个选择器,也可能就是一个DOM对象
this.$el = typeof options.el === 'string' ? document.querySelector(el)
: el
// 2. 把data中的成员转换成getter和setter,注入到 Vue 实例
this._proxyData(this.$data)
// 3. 调用 Observer 对象,监听数据的变化,实现数据劫持
new Observer(this.$data)
// 4. 调用 Compiler 对象,解析指令/插值表达式等
new Compiler(this)
}
// 代理数据,Vue代理data中的属性
_proxyData(data) {
// 遍历 data 的所有属性
Object.keys(data).forEach(key => {
// 把 data 的属性注入到 Vue实例中
// 这里的 this 就是Vue实例
Object.defineProperty(this, key, {
enumerable: true, // 是否可遍历
configurable: true, // 是否可配置
get() {
return data[key]
},
set(newValue) {
if (data[key] === newValue) {
return
}
data[key] = newValue
}
})
})
}
}
observer.js
// 负责数据劫持
// 把 $data 中的成员转换成 getter/setter
class Observer {
constructor(data) {
this.walk(data)
}
// 1. 判断数据是否是对象,如果不是对象返回,如果是空值,也返回
// 1.1. 如果是对象,遍历对象的所有属性,设置为 getter/setter
walk(data) {
if (!data || typeof data !== 'object') {
return
}
// 2. 遍历 data 的所有成员
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
// 定义响应式成员
defineReactive(data, key, val) {
const that = this
// 负责收集依赖,并发送通知
let dep = new Dep()
// 如果 val 是对象,继续设置它下面的成员为响应式数据
this.walk(val)
Object.defineProperty(data, key, {
configurable: true,
enumerable: true,
// 此处其实产生了闭包,所以val的值不会被释放掉
get() {
// 收集依赖,Dep.target就是观察者对象
Dep.target && dep.addSub(Dep.target)
return val // return val而不是data[key],因为returndata[key]会触发get方法,发生死递归,造成堆栈溢出
},
set(newValue) {
if (newValue === val) {
return
}
// 如果 newValue 是对象,设置 newValue 的成员为响应式
that.walk(newValue) // set 内部的this指向data对象
val = newValue
// 发送通知,因为在set方法中改变数据
dep.notify()
}
})
}
}
compiler.js
// 负责解析指令/插值表达式
class Compiler {
constructor(vm) {
this.vm = vm
this.el = vm.$el
// 立即编译模板
this.compile(this.el)
}
// 编译模板,处理文本节点和元素节点
compile(el) {
const nodes = el.childNodes
Array.from(nodes).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)
}
})
}
// 判断节点是否是文本节点
isTextNode(node) {
return node.nodeType === 3
}
// 判断节点是否是元素(属性)节点
isElementNode(node) {
return node.nodeType === 1
}
// 判断元素属性是否是指令 即,是否是以 v- 开头的指令
isDirective(attrName) {
return attrName.startsWith('v-')
}
// 编译文本节点,处理差值表达式
compileText(node) {
// 1. 匹配差值表达式 {{ msg }} 2. 要不花括号中变量的名字提取出来,后续要获取到这个变量的值
const reg = /\{\{(.+?)\}\}/ //.+后面的?号 表示非贪婪模式,尽可能早的结束匹配
// 获取文本节点的内容
const value = node.textContent
if (reg.test(value)) {
// 插值表达式中的值就是我们要的属性名称
const key = RegExp.$1.trim() // RegExp是正则的构造函数,RegExp.$1表示获取正则表达式中的第一个分组就是小括号中的内容
// 把插值表达式替换成具体的值
node.textContent = value.replace(reg, this.vm[key])
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
}
// 编译元素节点,处理指令
compileElement(node) {
// 遍历元素节点中的所有属性,找到指令
Array.from(node.attributes).forEach(attr => {
// 获取元素属性的名称
let attrName = attr.name
// 判断当前的属性名称是否是指令
if (this.isDirective(attrName)) {
// attrName 的形式 v-text v-model
// 截取属性的名称,获取 text model
attrName = attrName.substr(2)
// 获取属性的名称,属性的名称就是我们数据对象的属性 v-text="name",获取的是name
const key = attr.value
// 处理不同的指令
this.update(node, key, attrName)
}
})
}
// 负责更新 DOM
// 创建 Watcher
update(node, key, attrName) {
// node 节点,key 数据的属性名称,attrName 指令的后半部分
const updaterFn = this[attrName + 'Updater']
// updaterFn && updaterFn(node, this.vm[key], key)
updaterFn && updaterFn.call(this, node, this.vm[key], key)
}
// v-text 指令的更新方法 处理v-text指令把值取出来赋给对应DOM元素
textUpdater(node, value, key) {
node.textContent = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.textContent = newValue
})
}
// v-model 指令的更新方法
modelUpdater(node, value, key) {
node.value = value
// 创建watcher对象,当数据改变更新视图
new Watcher(this.vm, key, (newValue) => {
node.value = newValue
})
// 双向绑定——监听视图的变化
node.addEventListener('input', () => {
this.vm[key] = node.value
})
}
}
dep.js
class Dep {
constructor() {
// 存储所有的观察者
this.subs = []
}
// 添加观察者
addSub(sub) {
// 判断sub是否为空,并且有一个update方法(因为约定每个观察者都需要有一个update方法)
if (sub && sub.update) {
this.subs.push(sub)
}
}
// 通知所有观察者
notify() {
this.subs.forEach(sub => {
sub.update()
})
}
}
watche.js
class Watcher {
constructor(vm, key, cb) {
this.vm = vm
// data 中的属性名称
this.key = key
// 回调函数负责更新视图,当数据变化的时候,调用 cb 更新视图
this.cb = cb
// 在 Dep 的静态属性上记录当前 watcher 对象,当访问数据的时候把 watcher 添加到 dep 的 subs 中
Dep.target = this
// 触发一次 getter,让 dep 为当前 key 记录 watcher
this.oldValue = vm[key] // vm[key]会触发get方法,在get方法中会调用addSub
// 在把当前target添加到dep对象中之后,清空 target,防止将来重复添加
Dep.target = null
}
// 当数据变化的时候更新视图
update() {
const newValue = this.vm[this.key]
if (this.oldValue === newValue) {
return
}
this.cb(newValue)
}
}
文件明细
Vue 响应式原理——vue.js(第1部分)
Vue 响应式原理——observer.js(第2部分)
Vue 响应式原理——compiler.js(第3部分)
Vue 响应式原理——dep.js(第4部分)
Vue 响应式原理——watcher.js(第5部分)