体验vue几个流程,实现一个简易版💘
❓难点:watcher与dep联系建立的过程(可参考一下流程图)
简单的思路🤔

实现的过程(在自己的编辑器里看效果好)🔬
测试文件(自己建一个index.html)📜
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<div id="app">
<p @click="onclick">{{counter}}</p>
<p p-text="counter"></p>
<p p-html="desc"></p>
<input type="text" p-model="desc">
</div>
<script src="./pvue.js"></script>
<script>
const app = new PVue({
el: '#app',
data: {
counter: 1,
desc: '<p>你好<span style="color: blue">世界</span></p>'
},
})
setInterval(() => {
app.counter++
}, 1000);
</script>
结果演示地址📺
js代码实现部分展示(自己再建一个pvue.js)📜
function defineReactive(obj, key, val) {
observe(val)
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
console.log("get", key);
Dep.target && dep.addDep(Dep.target)
return val
},
set(v) {
if (v !== val) {
console.log("set", key, v);
val = v;
dep.notify()
}
}
})
}
function observe(obj) {
if (typeof obj !== "object" || obj === null) {
return
}
new Observer(obj)
}
class Observer {
constructor(obj) {
this.value = obj
if (Array.isArray(obj)) { } else {
this.walk(obj)
}
}
walk(obj) {
Object.keys(obj).forEach((key) => {
defineReactive(obj, key, obj[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 PVue {
constructor(options) {
this.$options = options
this.$data = options.data
observe(this.$data)
proxy(this)
new Compile(options.el, this)
}
}
class Compile {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
this.compile(this.$el)
}
compile(el) {
el.childNodes.forEach(node => {
if (node.nodeType === 1) {
this.compileElement(node)
if (node.childNodes.length > 0) {
this.compile(node)
}
} else if (this.isInter(node)) {
this.compileText(node)
}
})
}
isInter(node) {
console.warn(); ('检测插值语法');
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
}
isDir(attrName) {
console.warn('检测元素标签');
return attrName.startsWith('p-')
}
update(node, exp, dir) {
const fn = this[dir + "Updater"]
fn && fn(node, this.$vm[exp])
new Watcher(this.$vm, exp, function (val) {
fn && fn(node, val)
})
}
text(node, exp) {
this.update(node, exp, 'text')
}
textUpdater(node, val) {
node.textContent = val
}
html(node, exp) {
this.update(node, exp, 'html')
}
htmlUpdater(node, val) {
node.innerHTML = val
}
compileText(node) {
this.update(node, RegExp.$1, 'text')
}
compileElement(node) {
const nodeAttrs = node.attributes
Array.from(nodeAttrs).forEach(attr => {
const attrName = attr.name
const exp = attr.value
if (this.isDir(attrName)) {
const dir = attrName.substring(2)
this[dir] && this[dir](node, exp)
}
})
}
}
class Watcher {
constructor(vm,key,updateFn){
this.vm = vm
this.key = key
this.updateFn = updateFn
Dep.target = this
this.vm[this.key]
Dep.target = null
}
update(){
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())
}
}
点赞支持👍