一、双向数据绑定的原理分析
- 双向数据绑定:建立在单向数据绑定的基础之上的,也就是在
model-->View
的基础之上的。
- 双向数据绑定的实现过程:
- 在解析
v-model
指令时, 给当前元素添加 input
监听
- 当
input
的 value
发生改变时, 将最新的值赋值给当前表达式所对应的 data
属性
- 实现双向数据绑定,核心过程如下:
model: function (node, vm, exp) {
this.bind(node, vm, exp, 'model');
var me = this,
val = this._getVMVal(vm, exp);
node.addEventListener('input', function (e) {
var newValue = e.target.value;
if (val === newValue) {
return;
}
me._setVMVal(vm, exp, newValue);
val = newValue;
});
},
_setVal()
的核心实现:
_setVMVal: function (vm, exp, value) {
var val = vm._data;
exp = exp.split('.');
exp.forEach(function (k, i) {
if (i < exp.length - 1) {
val = val[k];
} else {
val[k] = value;
}
});
}
二、双向数据绑定的实现:
- 双向数据绑定:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>双向数据绑定</title>
</head>
<body>
<div id="test">
<input type="text" v-model="msg" />
<p>{{ msg }}</p>
</div>
</body>
<script type="text/javascript" src="./js/mvvm/compile.js"></script>
<script type="text/javascript" src="js/mvvm/mvvm.js"></script>
<script type="text/javascript" src="./js/mvvm/observer.js"></script>
<script type="text/javascript" src="./js/mvvm/watcher.js"></script>
<script type="text/javascript">
new MVVM({
el: "#test",
data: {
msg: "hahaha"
}
})
</script>
</html>