笔者也是第一次学习这个原理,听不懂的东西还挺多的,所以代码能用的就用,视频文章尾部自取。
视频中所讲的代码,大致如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model="school.name">
<div class="">{{school.name}}</div>
<div class="">{{school.age}}</div>
<!-- 如果数据不变化,视图就不会刷新 -->
{{getNewName}}
<!-- -->
<ul>
<li>1</li>
<li>1</li>
</ul>
<button v-on:click="change">update</button>
<div class="" v-html="message"></div>
</div>
<script src="./mvvm.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
school: {
name: 'vue',
age: 10
},
message: '<h1>JS</h1>'
},
computed: {
getNewName() {
return this.school.name + '3.0'
}
},
methods: {
change() {
this.school.name = 'react'
}
},
});
</script>
</body>
</html>
mvvm.js
// 观察者(发布订阅)
class Dep {
constructor() {
// 存放所有的 watcher
this.subs = []
}
// 订阅
addSub(watcher) {
// 添加 watcher
this.subs.push(watcher)
}
// 发布
notify() {
this.subs.forEach(watcher => watcher.update())
}
}
// new Watcher
class Watcher {
constructor(vm, expr, cb) {
this.vm = vm
this.expr = expr
this.cb = cb
// 默认存放旧值
this.oldValue = this.get()
}
get() {
Dep.target = this // 先把自己放在 this 上
// 取值 把这个观察者和 数据关联起来
let value = CompileUtil.getVal(this.vm, this.expr)
Dep.target = null
return value
}
// 更新操作 数据变化后,会调用观察者的 update 方法
update() {
let newVal = CompileUtil.getVal(this.vm, this.expr)
if (newVal !== this.oldValue) {
this.cb(newVal)
}
}
}
// vm.$watch(vm, 'school.name', (newVal) => {
// })
// 实现数据劫持功能
class Observer{
constructor(data) {
this.observer(data)
}
observer(data) {
// 如果是对象,才进行观察
if (data && typeof data === 'object') {
// 如果是对象
for (let key in data) {
this.defineReactive(data, key, data[key])
}
}
}
defineReactive(obj, key, value) {
this.observer(value)
let dep = new Dep(value) // 给每一个属性,都加上一个具有发布订阅的功能
Object.defineProperty(obj, key, {
get() {
// 创建 watcher时,会取到相对应的内容,并且把 watcher 放到全局上
Dep.target && dep.addSub(Dep.target)
return value
},
set:(newVal) => {
if (newVal != value) {
this.observer(newVal)
value = newVal
dep.notify()
}
}
})
}
}
// 基类 调度
class Compiler {
constructor(el, vm) {
// 判断 el 属性, 是不是一个元素, 如果不是元素, 进行获取
this.el = this.isElementNode(el) ? el : document.querySelector(el)
// 将当前节点的元素,获取之后存放到内存中
this.vm = vm
let fragment = this.node2fragment(this.el)
// 将节点中的内容进行替换
// 编译模板 用数据编译
this.compile(fragment)
// 把页面重新渲染到页面中
this.el.appendChild(fragment)
}
isDirective(attrName) {
return attrName.startsWith('v-')
}
// 编译元素
compileElement(node) {
let attributes = node.attributes;
[...attributes].forEach(attr => {
// console.log(attr)
let { name, value: expr } = attr
// console.log(name, value)
if (this.isDirective(name)) {
// console.log(node, 'element')
let [, directive] = name.split('-')
let [directiveName, eventName] = directive.split(':')
// 需要调用不同的指令来处理
CompileUtil[directiveName](node, expr, this.vm, eventName)
}
})
}
// 编译文本 包含 {{}}
compileText(node) {
let content = node.textContent
// console.log(content, 'text')
if (/\{\{(.+?)\}\}/.test(content)) {
console.log(node, 'text')
// 找到所有文本
CompileUtil['text'](node, content, this.vm)
}
}
// 编译内存中的 dom 节点
compile(node) {
let childNodes = node.childNodes;
// 类数组,转为数组
[...childNodes].forEach(child => {
if (this.isElementNode(child)) {
this.compileElement(child)
// 如果是元素的话,继续遍历子节点
// 递归调用
this.compile(child)
} else {
this.compileText(child)
}
})
// console.log(childNodes)
}
node2fragment(node) {
// 创建一个文档碎片
let fragment = document.createDocumentFragment()
let firstChild
while (firstChild = node.firstChild) {
// console.log(firstChild)
// appChild 具有移动性。从页面中获取,存放到内存中,页面的元素就会少一个
fragment.appendChild(firstChild)
}
return fragment
}
// 判断是否是元素节点
isElementNode(node) {
return node.nodeType === 1
}
}
CompileUtil = {
// 根据表达式取到对应的数据
getVal(vm, expr) {
// vm.$data
return expr.split('.').reduce((data, current) => {
return data[current]
}, vm.$data)
},
setValue(vm, expr, value) {
expr.split('.').reduce((data, current, index, arr) => {
if (index === arr.length - 1) {
return data[current] = value
}
return data[current]
}, vm.$data)
},
// 解析 v-model 指令
model(node, expr, vm) {
// node 是节点 expr 是表达式 vm 是当前实例,
let fn = this.updater['modelUpdater']
new Watcher(vm, expr, (newVal) => {
// 给输入框加一个观察者,如果数据更新了,会触发此方法
// 会各输入框赋予心智
fn(node, newVal)
})
node.addEventListener('input', (e) => {
let value = e.target.value // 获取用户输入的内容
this.setValue(vm, expr, value)
})
let value = this.getVal(vm, expr)
fn(node, value)
},
html(node, expr, vm) {
let fn = this.updater['htmlUpdater']
new Watcher(vm, expr, (newVal) => {
fn(node, newVal)
})
let value = this.getVal(vm, expr)
fn(node, value)
},
getContentValue(vm, expr) {
// 遍历表达式,将内容重新替换成完整的内容,返还回去
return expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
return this.getVal(vm, args[1])
})
},
on(node, expr, vm, eventName) {
// v-on:click="change"
node.addEventListener(eventName, (e) => {
vm[expr].call(vm, e) // this change
})
},
text(node, expr, vm) {
// expr => {{a}} {{b}} {{c}}
let fn = this.updater['textUpdater']
let content = expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
// 给表达式 {{}} 都加上观察者
new Watcher(vm, args[1], () => {
fn(node, this.getContentValue(vm, expr)) // 返回一个全的字符串
})
return this.getVal(vm, args[1])
})
fn(node, content)
},
updater: {
// 把数据插入到节点中
modelUpdater(node, value) {
node.value = value
},
htmlUpdater(node, value) {
node.innerHTML = value
},
textUpdater(node, value) {
node.textContent = value
}
}
}
class Vue {
constructor(optinos) {
// this.$el $data $options
this.$el = optinos.el
this.$data = optinos.data
let computed = optinos.computed
let methods = optinos.methods
// 如果根元素 存在 进行编译模板
if (this.$el) {
// 把数据全部转化为 Object.defineProperty 来定义
new Observer(this.$data)
// 把数据获取操作 vm 上的取值操作都代理到 vm.$data
//
for(let key in computed) {
Object.defineProperty(this.$data, key, {
get:() => {
return computed[key].call(this)
}
})
}
for(let key in methods) {
Object.defineProperty(this, key, {
get() {
return methods[key]
}
})
}
this.proxyVm(this.$data)
console.log(this.$data)
new Compiler(this.$el, this)
}
}
proxyVm(data) {
for(let key in data) {
// 取值可以通过 vm 取到相对应的值
Object.defineProperty(this, key, {
get() {
// 进行转化操作
return data[key]
},
set(newVal) {
data[key] = newVal
}
})
}
}
}
链接:https://pan.baidu.com/s/1tHs97yC21DaObE58PwtJcg
提取码:50mn