VUE双向绑定原理_vue的数据绑定怎么实现

VUE双向绑定原理_vue的数据绑定怎么实现烂大街原理 数据劫持 发布订阅者模式 obect defineProper 此处省略 8888 个字节 话不多说上代码 HTML JS 仿 vue 数据初始化 const app new Vue el app data myText 数据响应式 myBox 我是一个盒子 核心 发布订阅者模式 发布订阅者设计模式

烂大街原理:数据劫持+发布订阅者模式 (obect.defineProperty())……..(此处省略8888个字节)。

话不多说上代码

HTML:







JS:仿vue数据初始化

const app = new Vue({
el:'#app',
data:{
myText:'数据响应式',
myBox:'我是一个盒子'
}
})

核心:发布订阅者模式

//		发布订阅者设计模式
// 发布者化整为零,
class Vue{
constructor(options){
this.options = options;
this.$data = options.data;
this.$el = document.querySelector(options.el);
this._directive = {};

this.Observer(this.$data);
this.Complie(this.$el);
}
//劫持数据
Observer(data){
for( let key in data ){
this._directive[key] = [];
console.log(this._directive)
let Val = data[key];
let watch = this._directive[key];
Object.defineProperty(this.$data, key, {
get : function(){
return Val;
},
set : function(newVal){
if( newVal !== Val ){//新值不等于老值
Val = newVal;
//更新视图
console.log(watch,'watch')
watch.forEach(element => {
element.update();
})
}
}
})
}
}
//解析指令
Complie(el){
let nodes = el.children;
for(let i = 0;i < nodes.length; i++){
let node = nodes[i];
if( nodes[i].children){
this.Complie(nodes[i]);
}
if(node.hasAttribute("v-text")){
// console.log(1)
let attrVal = node.getAttribute('v-text');
this._directive[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'));
// console.log(this._directive);
}
if(node.hasAttribute("v-model")){
let attrVal = node.getAttribute('v-model');
this._directive[attrVal].push(new Watcher(node,this,attrVal,'value'));
// console.log(this._directive);
node.addEventListener('input',(function(){
return function(){
console.log(1);
this.$data[attrVal] = node.value;
}
})().bind(this));

}
}
}
}
// 订阅者
class Watcher{
// div.innerHTML = vue对象.$data['myText'];
constructor(el, vm, exp, attr){
this.el = el;
this.vm = vm;
this.exp = exp;
this.attr = attr;
this.update();
}
update(){
this.el[this.attr] = this.vm.$data[this.exp];
}
}

浏览器展示效果:

编程小号
上一篇 2025-03-08 17:57
下一篇 2025-03-04 14:33

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/131507.html