vue响应式的整个流程的简易实现
如果对文章中有不懂的思路或者函数,可以对应的去看看我其他的文章。
// index.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>Document</title>
</head>
<body>
<div id="app"></div>
<script src="./render.js"></script>
<script src="./vue2_响应式简易实现.js"></script>
<script src="./index.js"></script>
<script>
// 1. 根组件
const App = {
data: reactive({
counter: 1
}),
// render函数的返回值是一个VNode
render() {
return h("div", null, [
h("h2", null, `当前计数: ${this.data.counter}`),
h("button", {
onclick: () => {
this.data.counter++
}
}, "+1")
])
}
}
// 2.挂载根组件
const app = createApp(App)
app.mount("#app")
</script>
</body>
</html>
// index.js
// createApp方法返回一个对象,这个对象包含一个mount方法
function createApp(rootComponent) {
return {
mount(selector) {
const rootEl = document.querySelector(selector)
let isMounted = false // 是否挂载
let oldVNode = null // 旧的VNode
// counter的订阅者是通过counter的get函数
// counter的发布者是通过counter的set函数通知订阅者更新数据
watchEffect(function () {
// 如果虚拟节点没有挂载,就挂载,如果挂载了,就执行patch操作
if (!isMounted) {
oldVNode = rootComponent.render()
mount(oldVNode, rootEl)
isMounted = true
} else {
const newVNode = rootComponent.render() // 新的VNode
patch(oldVNode, newVNode)
oldVNode = newVNode
}
})
}
}
}
// render.js
// h函数的作用就是将compiler编译后的模板转为vnode(也就是js对象)
function h(tag, property, children) {
return {
tag,
property,
children
}
}
// 虚拟DOM转为真实DOM
function mount(vnode, container) {
// 1. 将tag转为标签
const el = vnode.el = document.createElement(vnode.tag)
// 2. 给标签设置对应的属性
if (vnode.property) {
for (const key in vnode.property) {
const value = vnode.property[key]
// 点击事件
if (key.startsWith("on")) {
el.addEventListener(key.slice(2), value)
console.log(el.click)
} else {
el.setAttribute(key, value)
}
}
}
// 3. 处理children
if (vnode.children) {
if (typeof vnode.children === 'string' || typeof vnode.children === 'number') {
el.textContent = vnode.children
} else {
vnode.children.forEach(item => {
mount(item, el)
});
}
}
// 4. 将节点挂载到父节点上
container.appendChild(el)
}
// diff算法(最简易实现,同层级,不包含key属性的节点)
// vnode1是oldVNode, vnode2是newVNode
const patch = (vnode1, vnode2) => {
// 判断是否是同一种标签
if (vnode1.tag !== vnode2.tag) {
// 移除oldVNode,添加newVNode
const elParentEl = vnode1.el.parentElement
elParentEl.removeChild(vnode1.el)
mount(vnode2, elParentEl)
} else {
// el是引用,在修改el时,同时修改oldVNode,newVNode(目的是:在oldVNode上直接实现DOM更新)
// el就是最终需要的结果
const el = vnode2.el = vnode1.el
// 处理newVNode property(标签的属性),给el添加newVNode的属性
for (const key in vnode2.property) {
const newValue = vnode2.property[key]
const oldValue = vnode1.property[key]
if (newValue !== oldValue) {
// 对事件属性做单独处理
if (key.startsWith("on")) {
el.addEventListener(key.slice(2), vnode2.property[key])
} else {
el.setAttribute(key, newValue)
}
}
}
// 处理oldVNode property(标签的属性),给el移除oldVNode的属性
for (const key in vnode1.property) {
if (key.startsWith("on")) {
el.removeEventListener(key.slice(2), vnode2.property[key])
}
if (!(key in vnode2.property)) {
// 对事件属性做单独处理
el.removeAttribute(key)
}
}
// 处理children
// 如果newVNode的children是string或者number类型
if (typeof vnode2.children === 'string' || typeof vnode1.children === 'number') {
el.innerHTML = vnode2.children
} else {
// 如果newVNode的children是array类型
/**
* 这儿就实现一种最最简单的情况:
* vnode不带有key属性
*/
// newVNode.length = oldVNode.length
const commonLength = Math.min(vnode1.children.length, vnode2.children.length)
for (let i = 0; i < commonLength; i++) {
patch(vnode1.children[i], vnode2.children[i])
}
// newVNode.length > oldVNode.length
if (vnode2.children.length > vnode1.children.length) {
const newChildren = vnode2.children.slice(commonLength)
newChildren.forEach(item => {
mount(item, el)
})
}
// newVNode.length < oldVNode.length
if (vnode2.children.length < vnode1.children.length) {
const oldChildren = vnode1.children.slice(commonLength)
oldChildren.forEach(item => {
el.remove(item.el)
})
}
}
}
}
// /vue2_响应式简易实现.js
class Dep {
constructor() {
// 订阅者
this.subscribers = new Set()
}
depend() {
if (activeEffect) {
this.subscribers.add(activeEffect)
}
}
notify() {
this.subscribers.forEach(fun => {
fun()
})
}
}
// 用来收集订阅者
let activeEffect = null
function watchEffect(effect) {
activeEffect = effect
effect()
activeEffect = null
}
/**
* WeakMap: 用来包裹传入的对象(垃圾回收机制)
* 传入的对象:是一个map对象(用来建立对应的映射)
* map对象:每一项都是一个Dep(发布者)
*
* 也就是说:getDep函数的作用就是给每一项数据都建立一个对应的发布者
*/
const targetMap = new WeakMap()
// 用来建立对应的发布者
function getDep(target, key) {
// 根据传入的对象,获取对应的map对象
let depsMap = targetMap.get(target)
if (!depsMap) {
depsMap = new Map()
// 给对应的map对象赋值
targetMap.set(target, depsMap)
}
// 获取key属性对应的dep对象(获取key对应的发布者)
let dep = depsMap.get(key)
if (!dep) {
dep = new Dep()
depsMap.set(key, dep)
}
return dep
}
// vue2
function reactive(raw) {
Object.keys(raw).forEach(key => {
let value = raw[key]
const dep = getDep(raw, key)
Object.defineProperty(raw, key, {
get() {
// 收集依赖
dep.depend()
return value
},
set(newValue) {
value = newValue
dep.notify()
}
})
})
return raw
}
// vue3
// function reactive(raw) {
// return new Proxy(raw, {
// get(target, key) {
// const dep = getDep(raw, key)
// dep.depend()
// return target[key]
// },
// set(target, key, newValue) {
// const dep = getDep(raw, key)
// target[key] = newValue
// dep.notify()
// }
// })
// }
// 测试代码
const info = reactive({ name: 'summer', age: 18 })
const info2 = reactive({ height: 1.88, weight: 188 })
watchEffect(function () {
console.log('effect1', info.name, info.age)
})
watchEffect(function () {
console.log('effect2', info2.height, info2.weight)
})
info.name = 'black'
// info2.height = 1.66
/**
* 思路:
* 1. 定义变量并赋值时,对变量进行截取(reactive),利用Object.defineProperty重写它的get和set方法
* get方法中dep.depend用于收集数据的依赖(订阅者)
* set方法中dep.notify用于通知订阅者更新数据
* 2. reactive方法中有getDep()方法的执行,getDep方法的目的是:给每个数据项建立一个对应的发布者
* 当执行这个函数的时候会传入两个参数:target目标对象,key目标对象中的属性,
* 第一次执行这个函数时,target还是普通对象,这时候将会将target转化为map对象,并且target和map-target作为targetMap的一个键值对,
* 这时候再将第一次执行的属性的属性值都设置为dep对象(发布者)
* 3. 类Dep,使用创建发布者(dep)和收集订阅者(subscribers)的,当一个数据被重新赋值时,就通过notify通知订阅者执行,更新数据
* Dep中的depend用于收集这个发布者(数据项)对应的所有订阅者
*/
如有错误,欢迎指正!