本文不会拆步骤对源码进行实现,只介绍vue原理及相关核心实现思想。在之前的四篇文章中已对vue进行响应实现。需要可阅读相关文章:
MVVM框架的三要素:数据响应式、模板引擎及其渲染。

数据响应式:监听数据变化并在视图中更新
模版引擎:提供描述视图的模版语法
渲染:如何将模板转换为html
数据变更能够响应在视图中,就是数据响应式。vue2中利用 Object.defineProperty() 实现变更检测。

原理分析:

涉及类型介绍:
编译模板中vue模板特殊语法,初始化视图、更新视图

视图中会用到data中某key,这称为依赖。同一个key可能出现多次,每次都需要收集出来用一个
Watcher来维护它们,此过程称为依赖收集。
多个Watcher需要一个Dep来管理,需要更新时由Dep统一通知。
看下面案例,理出思路:
new Vue({
template:
`<div>
<p>{{name1}}p>
<p>{{name2}}p>
<p>{{name1}}p>
<div>`,
data: {
name1: 'name1',
name2: 'name2'
}
});

// 数组响应式
const oldArrayProperty = Array.prototype
const arrayProto = Object.create(oldArrayProperty)
const methodsToPatch = ['push', 'pop', 'unshift', 'shift', 'sort', 'splice', 'reverse']
methodsToPatch.forEach(methodName => {
Object.defineProperty(arrayProto, methodName, {
value () {
console.log('you change the array')
oldArrayProperty[methodName].apply(this, arguments)
}
})
})
// 给一个obj定义一个响应式的属性
function defineReactive (obj, key, val) {
// 递归
// val如果是个对象,就需要递归处理
observe(val)
const dep = new Dep()
Object.defineProperty(obj, key, {
get () {
Dep.target && dep.addDep(Dep.target)
return val
},
set (newVal) {
if (newVal !== val) {
console.log('set', key, val)
val = newVal
// 新值如果是对象,仍然需要递归遍历处理
observe(newVal)
dep.notify()
// 暴力的写法,让一个人干事指挥所有人动起来
// watchers.forEach(watch => {
// watch.update()
// })
}
}
})
}
// 遍历响应式处理
function observe (obj) {
if (typeof obj !== 'object' || obj == null) {
return obj
}
new Observer(obj)
}
class Observer {
constructor (obj) {
// 判断传入obj类型,做相应处理
if (Array.isArray(obj)) {
Object.setPrototypeOf(obj, arrayProto)
// 对数组内部元素执行响应式
const keys = Object.keys(obj)
keys.forEach(key => observe(obj[key]))
} else {
this.walk(obj)
}
}
walk (obj) {
Object.keys(obj).forEach((key) => {
defineReactive(obj, key, obj[key])
})
}
}
// 能够将传入对象中的所有key代理到指定对象上
function proxy (vm) {
Object.keys(vm.$data).forEach((key) => {
Object.defineProperty(vm, key, {
get () {
return vm.$data[key]
},
set (v) {
vm.$data[key] = v
}
})
})
}
class MVue {
constructor (options) {
// 保存options
this.$options = options
this.$data = options.data
this.$methods = options.methods
// 将data进行响应式处理
observe(this.$data)
// 代理
proxy(this)
// 编译
new Compile(options.el, this)
}
}
class Compile {
constructor (el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
if (this.$el) {
this.compile(this.$el)
}
}
compile (node) {
// 找到该元素的子节点
const childNodes = node.childNodes
// childNodes是类数组对象
Array.from(childNodes).forEach(n => {
// 判断类型
if (this.isElment(n)) {
this.compileElement(n)
// 递归
if (n.childNodes.length > 0) {
this.compile(n)
}
} else if (this.isInter(n)) {
// 动态插值表达式 编译文本
this.compileText(n)
}
})
}
isElment (node) {
return node.nodeType === 1
}
isInter (n) {
return n.nodeType === 3 && /\{\{(.*)\}\}/.test(n.textContent)
}
isDir (attrName) {
return attrName.startsWith('m-')
}
isEvent (attrName) {
return attrName.startsWith('@')
}
// 编译元素:遍历它的所有属性,看是否k-开头指令,或者@事件
compileElement (node) {
const attrs = node.attributes
Array.from(attrs).forEach(attr => {
// m-text="XXX"
// name = m-text, value=xxx
const attrName = attr.name
const exp = attr.value
// 是指令
if (this.isDir(attrName)) {
// 执行特定指令处理函数
const dir = attrName.substring(2)
this[dir] && this[dir](node, exp)
} else if (this.isEvent(attrName)) {
const event = attrName.substring(1)
// node['on' + event] = this.$vm.$methods[exp]
// 通过bind改变this指向为vm实例,以便方法内部访问vm.data中的数据
node.addEventListener(event, this.$vm.$methods[exp].bind(this.$vm))
}
})
}
update (node, exp, dir) {
// 第一步: 初始化值
const fn = this[dir + 'Updater']
fn && fn(node, this.$vm[exp])
// 第二步: 更新
new Watcher(this.$vm, exp, val => {
fn && fn(node, val)
})
}
compileText (n) {
// 获取表达式
// n.textContent = this.$vm[RegExp.$1]
// n.textContent = this.$vm[RegExp.$1.trim()]
this.update(n, RegExp.$1.trim(), 'text')
}
text (node, exp) {
this.update(node, exp, 'text')
// node.textContent = this.$vm[exp] || exp
}
textUpdater (node, val) {
node.textContent = val
}
html (node, exp) {
this.update(node, exp, 'html')
// node.innerHTML = this.$vm[exp]
}
htmlUpdater (node, val) {
node.innerHTML = val
}
model (node, exp) {
node.value = this.$vm[exp]
node.addEventListener('input', (e) => {
this.$vm[exp] = e.target.value
})
}
}
// // 监听器:负责依赖更新
// const watchers = []
// class Watcher {
// constructor (vm, key, updateFn) {
// this.vm = vm
// this.key = key
// this.updateFn = updateFn
// watchers.push(this)
// }
// update () {
// // 绑定作用域为this.vm,并且将this.vm[this.key]作为值传进去
// this.updateFn.call(this.vm, this.vm[this.key])
// }
// }
// 监听器:负责依赖更新
class Watcher {
constructor (vm, key, updateFn) {
this.vm = vm
this.key = key
this.updateFn = updateFn
// 触发依赖收集
Dep.target = this
// 触发一下get
this.vm[this.key]
Dep.target = null
}
update () {
// 绑定作用域为this.vm,并且将this.vm[this.key]作为值传进去
this.updateFn.call(this.vm, this.vm[this.key])
}
}
class Dep {
constructor () {
this.deps = []
}
addDep (dep) {
this.deps.push(dep)
}
notify () {
this.deps.forEach(dep => dep.update())
}
}
测试代码:
<!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>Document</title>
</head>
<body>
<div id="app">
<p>{{ counter }}</p>
<p m-text="测试"></p>
<p m-text="counter"></p>
<p m-html="desc"></p>
<p @click="test">点击我</p>
<input m-model="desc" />
</div>
</body>
<script src="./index.js"></script>
<script>
const app = new MVue({
el: '#app',
data: {
counter: 1,
desc: 'super wanan',
name: 'wanan',
arr: [{
name: 1,
arr: [12]
}]
},
methods: {
test() {
this.counter++;
console.log('进入了', this.counter)
this.arr.push(2)
this.arr[0].arr.push(2)
console.log('进入了', this.arr)
}
},
})
// setInterval(() => {
// app.counter++
// }, 1000)
</script>
</html>