来一张原理图:

实现思路:

  (1)绑定data 种的数据,为每个数据添加指令。通过Object,defineProperty() 来通知属性是否更改

  (2) 找到每个DOM节点的指令。绑定事件。并绑定watcher

  (3)  实现DOM事件改变之后, 响应data数据,实现视图更新

<!DocType>
<html>
<title>vue 的双向绑定事件</title>
<body id="app">
<input type="text" v-model="number"/>
<span v-bind="number"></span>
<input type="text" v-model="age"/>
<span v-bind="age"></span>
</body> <script>
function Vue (options) {
this._init(options);
} Vue.prototype._init = function (options) {
this.$data = options.data;
this.$methods = options.data.methods;
this.$el = document.querySelector(options.el);
this.$methods = options.methods;
this.$key = ''; this._binding = {}; // 观测数据
this._observer(this.$data); this._complie(this.$el); // this._test(this.$data);
} // 观测数据
Vue.prototype._observer = function (obj) {
var value;
let _this = this;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
this._binding[key] = {
_directives: []
};
value = obj[key];
if (typeof value === 'object') {
this._observer(value);
}
Object.defineProperty(this.$data, key, {
enumerable: true,
configurable: true,
get: function () {
console.log(`获取${value}`, key);
return value;
},
set: function (newVal) {
console.log('key:', key, _this.$key);
if (value !== newVal) {
value = newVal;
_this._binding[_this.$key]._directives.forEach(function (item, index) {
item.update();
})
}
}
})
}
}
} // 为DOM节点添加指令事件
Vue.prototype._complie = function (root) {
var _this = this;
var nodes = root.children;
for (var i = ; i < nodes.length; i++) {
var node = nodes[i];
if (node.children.length) {
this._complie(node);
} if (node.hasAttribute('v-click')) {
node.onclick = (function () {
var attrVal = nodes[i].getAttribute('v-click');
return _this.$methods[attrVal].bind(_this.$data);
})();
} if (node.hasAttribute('v-model') && (node.tagName == 'INPUT' || node.tagName == 'TEXTAREA')) {
node.addEventListener('input', (function(key) {
var attrVal = node.getAttribute('v-model');
_this._binding[attrVal]._directives.push(new Watcher(
'input',
node,
_this,
attrVal,
'value'
)) return function() {
_this.$key = attrVal
_this.$data[attrVal] = nodes[key].value;
}
})(i));
} if (node.hasAttribute('v-bind')) {
var attrVal = node.getAttribute('v-bind');
_this._binding[attrVal]._directives.push(new Watcher(
'text',
node,
_this,
attrVal,
'innerHTML'
))
}
}
} function Watcher(name, el, vm, exp, attr) {
this.name = name; //指令名称,例如文本节点,该值设为"text"
this.el = el; //指令对应的DOM元素
this.vm = vm; //指令所属myVue实例
this.exp = exp; //指令对应的值,本例如"number"
this.attr = attr; //绑定的属性值,本例为"innerHTML" this.update();
} // 更新数据
Watcher.prototype.update = function () {
this.el[this.attr] = this.vm.$data[this.exp];
} // 测试
Vue.prototype._test = function($data) {
var a = $data.number;
$data.number = ;
} window.onload = function () {
var app = new Vue({
el: '#app',
data: {
number: ,
age:
},
methods: {}
})
} </script>
</html>

手写vue双向绑定数据的更多相关文章

  1. vue双向绑定(数据劫持+发布者-订阅者模式)

    参考文献:https://www.cnblogs.com/libin-1/p/6893712.html 实现mvvm主要包含两个方面,数据变化更新视图,视图变化更新数据. 关键点在于data如何更新v ...

  2. vue 双向绑定 数据修改但页面没刷新

    在数据改动的代码后加 this.$forceUpdate(); 若是在某个特定方法中 则将this改为方法中设定的名称

  3. 用ES6的class模仿Vue写一个双向绑定

    原文地址:用ES6的class模仿Vue写一个双向绑定 点击在线尝试一下 最终效果如下: 构造器(constructor) 构造一个TinyVue对象,包含基本的el,data,methods cla ...

  4. vue 结合localStorage 来双向绑定数据

    结合localStorage 来双向绑定数据(超级神奇) localStorage.js: const STORAGE_KEY = 'todos_vuejs' export default { fet ...

  5. 组件的通信 :provide / inject 对象进入后,就等于不用props,然后内部对象,直接复制可以接受数组,属性不能直接复制,可以用Object.assgin覆盖对象,或者Vue的set 双向绑定数据

    组件的通信 :provide / inject 对象进入后,就等于不用props,然后内部对象,直接复制可以接受数组,属性不能直接复制,可以用Object.assgin覆盖对象,或者Vue的set 双 ...

  6. [Vue源码]一起来学Vue双向绑定原理-数据劫持和发布订阅

    有一段时间没有更新技术博文了,因为这段时间埋下头来看Vue源码了.本文我们一起通过学习双向绑定原理来分析Vue源码.预计接下来会围绕Vue源码来整理一些文章,如下. 一起来学Vue双向绑定原理-数据劫 ...

  7. 最近老是有兄弟问我,Vue双向绑定的原理,以及简单的原生js写出来实现,我就来一个最简单的双向绑定,原生十行代码让你看懂原理

    废话不多说直接看效果图 代码很好理解,但是在看代码之前需要知道Vue双向绑定的原理其实就是基于Object.defineProperty 实现的双向绑定 官方传送门 这里我们用官方的话来说Object ...

  8. 剖析手写Vue,你也可以手写一个MVVM框架

    剖析手写Vue,你也可以手写一个MVVM框架# 邮箱:563995050@qq.com github: https://github.com/xiaoqiuxiong 作者:肖秋雄(eddy) 温馨提 ...

  9. 手写 Vue 系列 之 Vue1.x

    前言 前面我们用 12 篇文章详细讲解了 Vue2 的框架源码.接下来我们就开始手写 Vue 系列,写一个自己的 Vue 框架,用最简单的代码实现 Vue 的核心功能,进一步理解 Vue 核心原理. ...

随机推荐

  1. HBase概念学习(九)HTablePool为何弃用?

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/jiq408694711/article/details/36526433 转载请注明出处:jiq•钦 ...

  2. 小米3系统计算器自己定义开关控件-MySwitchView

    1.前言             在android4.0以后,有switch控件.相似于iPhone上面滑块的效果.可是仅仅能用在4.0以后的系统中.之前的平台.就无法使用这种控件. 近段时间.看到了 ...

  3. 关于军训的模拟赛-R2

    终于我也参加了一场有R1 && R2的比赛呢. 点击此处查看R1 因为种种原因,老师认为上次的考试没有体现我们的真实水平,于是举办了毒瘤R2,其实也不是非常毒瘤,还是一贯的风格. T1 ...

  4. PHP安全过滤函数

    在PHP中,有些很有用的函数开源非常方便的防止你的网站遭受各种攻击,例如SQL注入攻击,XSS(Cross Site Scripting:跨站脚本)攻击等.   1. mysql_real_escap ...

  5. Docker Java应用日志时间和容器时间不一致

    1.在docker容器和系统时间不一致是因为docker容器的原生时区为0时区,而国内系统为东八区. 2.还有容器中运行的java应用打出的日志时间和通过date -R方式获取的容器标准时间有八个小时 ...

  6. 企业案例--生产环节更改mysql字符集

    查看数据库字符集: show database create dbname \G; 查看数据库表字符集: show table create tbname \G; 查看现有数据库字符集设置: show ...

  7. windows10 安装 Anaconda 并配置 pytorch1.0

    官网下载Anaconda安装包,按步骤安装即可安装完后,打开DOS,或Anaconda自带的Anaconda Prompt终端查看Anaconda已安装的安装包C:\Users\jiangshan&g ...

  8. 前端:background 设置

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. scrollIntoView()的用法

    scrollIntoView是一个与页面(容器)滚动相关的API(官方解释),该API只有boolean类型的参数能得到良好的支持(firefox 36+都支持),所以在这里只讨论参数Boolean类 ...

  10. 关于Flume中Chanel.Selector.header解释

    flume内置的ChannelSelector有两种,分别是Replicating和Multiplexing. Replicating类型的ChannelSelector会针对每一个Event,拷贝到 ...