Vue2的双向数据绑定

Vue2的双向数据绑定

  • Observer:观察者,这里的主要工作是递归地监听对象上的所有属性,在属性值改变的时候,触发相应的watcher。

  • Watcher:订阅者,当监听的数据值修改时,执行响应的回调函数(Vue里面的更新模板内容)。

  • Dep:订阅管理器,连接Observer和Watcher的桥梁,每一个Observer对应一个Dep,它内部维护一个数组,保存与该Observer相关的Watcher

/* 实现数据监听器(数据劫持)*/
	function Observer(obj, key, value) {
   
  		var dep = new Dep();
  		if (Object.prototype.toString.call(value) == '[object Object]') {
   
   		    Object.keys(value).forEach(function(key) {
   
      		new Observer(value, key, value[key])
    	 })
  	 };

  	Object.defineProperty(obj, key, {
   
   		 enumerable: true,
   		 configurable: true,
    	  get: function() {
   
     		 if (Dep.target) {
   
        	 dep.addSub(Dep.target);
      	     };
      	     return value;
          },
    	set: function(newVal) {
   
      		value = newVal;
      		dep.notify();
    		}
  		})
	}
	
	// 订阅器
	function Dep() {
   
  		this.subs = [];
  		this.addSub = function (watcher) {
   
    		this.subs.push(watcher);
  		}

  		this.notify = function() {
   
    		this.subs.forEach(function(watcher) {
   
    			watcher.update();
    		});
  		}
	}

	// 观察者
   function Watcher(fn) {
   
 	 	this.update = function() {
   
    		Dep.target = this;
    		fn();
    		Dep.target = null;
  		}
  		this.update();
	}

	// 连接器
	<div id="app">
  		<input id="input" type="text" v-model="text">
  		<div id="text">输入的值为:{
   {
   text}}</div>
	</div>
	<script type="text/javascript">
  		var obj = {
   
    		text: 'hello world'
  		}
  		Object.keys(obj).forEach(function(key){
   
  	  		new Observer(obj, key, obj[key])
  		});
  		new Watcher(function(){
   
    		document.querySelector("#text").innerHTML = "输入的值为:" + obj.text;
  		})
 		 document.querySelector("#input").addEventListener('input', function(e) {
   
    		obj.text = e.target.value;
  		})
	</script>

在这里插入图片描述

相关推荐

  1. vue2 双向数据实现及原理

    2024-01-21 08:32:04       12 阅读
  2. Vue双向数据原理

    2024-01-21 08:32:04       45 阅读
  3. Vue 双向数据

    2024-01-21 08:32:04       19 阅读
  4. Vue2Vue3 双向数据区别和原理

    2024-01-21 08:32:04       20 阅读
  5. vue双向数据原理(v2、v3)

    2024-01-21 08:32:04       11 阅读
  6. Vue双向数据原理

    2024-01-21 08:32:04       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-21 08:32:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-21 08:32:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-21 08:32:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-21 08:32:04       20 阅读

热门阅读

  1. C#设计模式教程(10):装饰器模式

    2024-01-21 08:32:04       32 阅读
  2. Webpack5入门到原理15:提取 Css 成单独文件

    2024-01-21 08:32:04       38 阅读
  3. vue对axios进行二次封装

    2024-01-21 08:32:04       29 阅读
  4. 一文详解pyspark中sql的join

    2024-01-21 08:32:04       33 阅读
  5. 探索Flask中的RESTful API设计与实现

    2024-01-21 08:32:04       34 阅读
  6. hive order by length() 报错

    2024-01-21 08:32:04       30 阅读
  7. C++核心编程

    2024-01-21 08:32:04       26 阅读
  8. 【笔记】Helm-3 主题-11 基于角色的访问控制

    2024-01-21 08:32:04       28 阅读