前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VUE双向绑定原理_vue的数据绑定怎么实现

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

作者头像
全栈程序员站长
发布2022-10-05 10:06:43
8950
发布2022-10-05 10:06:43
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

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

话不多说上代码

HTML:

代码语言:javascript
复制
<div id="app">
	<div>
	    <div v-text="myText"></div>
	    <div v-text="myBox"></div>
		<input type="text" v-model="myText">
	</div>
</div>

JS:仿vue数据初始化

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

核心:发布订阅者模式

代码语言:javascript
复制
//		发布订阅者设计模式
//		发布者化整为零,
		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];
			}
		}

浏览器展示效果:

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月14日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档