vue双向数据绑定知识点总结

2020-06-14 05:57:15易采站长站整理

node.onclick = (function () {
var attrVal = node.getAttribute('v-click');
console.log(attrVal);
// bind让data的作用域与method函数的作用域保持一致
return _this.$method[attrVal].bind(_this.$data);
})();
};
// 如果有v-model属性;并且元素是input或者textrea;我们监听他的input事件
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 xhWatcher(
'input',
node,
_this,
attrVal,
'value'
));
return function () {
// 让number的值和node的value保持一致;就实现了双向数据绑定
_this.$data[attrVal] = nodes[key].value
}
})(i));
};
// 如果有v-bind属性;我们要让node的值实时更新为data中number的值
if (node.hasAttribute('v-bind')) {
var attrVal = node.getAttribute('v-bind');
_this._binding[attrVal]._directives.push(new xhWatcher(
'text',
node,
_this,
attrVal,
'innerHTML'
))
}
}
}

function xhWatcher(name, el, vm, exp, attr) {
this.name = name; // 指令名称;对于文本节点;例如text
this.el = el; // 指令对应DOM元素
this.vm = vm; // 指令所属vue实例
this.exp = exp; // 指令对应的值;例如number
this.attr = attr; // 绑定的属性值;例如innerHTML
this.update();
}
xhWatcher.prototype.update = function () {
this.el[this.attr] = this.vm.$data[this.exp];
// 例如h3的innerHTML = this.data.number;当numner改变则会触发本update方法;保证对应的DOM实时更新
}
var app = new xhVue({
el: '#app',
data: {
number: 0
},
methods: {
increment: function () {
this.number++;
}
}
});
</script>

</html>

所有的代码;复制到编辑器就可查看效果了~~