// dom
<input id="input" type="text">
<input id="input1" type="text">
<div id="box"></div>
<div id="box1"></div>
// 实现基础版vue 发布订阅模式
class Dep { // 订阅者
constructor() {
this.subs = []
}
add(sub) {
this.subs.push(sub)
}
publish() {
this.subs.forEach((item) => {
item.updata()
})
}
}
Dep.target = null
class OberServes { // 中间人
constructor(obj = {}) {
Object.keys(obj).forEach((item) => {
setData(obj, item, obj[item])
})
}
}
function setData(obj, key, value) {
const dep = new Dep()
let data = oberServe(value)
Object.defineProperty(obj, key, {
get() {
if (Dep.target) {
dep.add(Dep.target)
}
return value
},
set(newValue) {
if (value === newValue) return
data = oberServe(newValue)
value = newValue
dep.publish()
}
})
}
function oberServe(obj) {
if (obj !== null && typeof obj === 'object') {
return new OberServes(obj)
}
}
class Watcher { // 观察者
constructor(vm, key, fn) {
this.vm = vm
this.key = key
this.fn = fn
Dep.target = this
this.updata()
Dep.target = null
}
updata() {
this.value = this.get()
this.fn(this.value)
}
get() {
return this.vm[this.key]
}
}
class Vue { // vue
constructor(options = {}) {
let data = this.data = options.data
new oberServe(data)
Object.keys(data).forEach((item) => {
this.$setData(this, item)
})
}
$setData(obj, key) {
Object.defineProperty(obj, key, {
get() {
return obj.data[key]
},
set(newValue) {
if (obj.data[key] === newValue) return
obj.data[key] = newValue
}
})
}
}
const vm = new Vue({ // 实例化
data: { txt: '1', txt1: '1' }
})
document.querySelector('#input').addEventListener('keyup', function (e) {
vm.txt = e.target.value
})
document.querySelector('#input1').addEventListener('keyup', function (e) {
vm.txt1 = e.target.value
})
new Watcher(vm, 'txt', (e) => document.querySelector('#box').innerHTML = e)
new Watcher(vm, 'txt1', (e) => document.querySelector('#box1').innerHTML = e)
Vue简化版实现
最新推荐文章于 2024-04-04 09:41:33 发布