Vue 数据响应
Vue数据响应原理 :
1、通过 Object.defineProperty()方法改为 get set 方式获取 state 状态
2、处理 state 与节点之间的映射关系
3、更新 state 的数据到页面节点上
html 部分
<div id="root">
<h1 data-on='a'></h1>
<h1 data-on='a'></h1>
<input type="text" name="" id="" i-module='a'>
<h1 data-on='conut'></h1>
<input type="text" name="" id="" i-module='conut'>
<h1 data-on='msg'></h1>
<input type="text" name="" id="" i-module='msg'>
</div>
js部分
1、 创建实例化对象
let App = new Vue({
el: '#root',
data() {
return {
a: 1,
conut: 2,
msg: 'hello'
}
}
})
2、state 的处理:==> 状态 初始化和更新并渲染到页面(处理数据)
class Vue {
constructor({ el, data } = {}) {
this.$el = document.querySelector(el);
this.$data = data();
this.init()
}
init() {
this.$ob = this.createObserver()
this.defineProperty()
}
createObserver() {
const that = this;
return {
swtcher: {
maps: {},
add(k, cb) {
if (this.maps[k]) {
this.maps[k].push(cb)
return;
}
this.maps[k] = [cb]
}
},
subscribe(k) {
that.$el.querySelectorAll(`[data-on=${k}]`).forEach(item => {
const cb = text => item.innerHTML = text
this.swtcher.add(k, cb)
})
that.$el.querySelectorAll(`[i-module=${k}]`).forEach(item => {
const cb = text => item.value = text
item.addEventListener('input', e => {
console.log(that[k]);
console.log(e.target.value);
that[k] = e.target.value
})
this.swtcher.add(k, cb)
})
this.emit(k)
},
emit(k) {
this.swtcher.maps[k].forEach(cb => cb(that[k]))
}
}
}
defineProperty() {
for (let k in this.$data) {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => this.$data[k],
set(value) {
if (value !== this.$data[k]) {
this.$data[k] = value
this.$ob.emit(k)
}
}
})
this.$ob.subscribe(k)
}
}
}
|