vue双向数据绑定知识点总结(3)
2.1 定义
首先我们需要定义一个xhVue的构造函数
function xhVue(options){
}
2.2 添加
为了初始化这个构造函数;给其添加一个_init属性
function xhVue(options){
this._init(options);
}
xhVue.prototype._init = function(options){
this.$options = options; // options为使用时传入的结构体;包括el,data,methods等
this.$el = document.querySelector(options.el); // el就是#app,this.$el是id为app的Element元素
this.$data = options.data; // this.$data = {number:0}
this.$methods = options.methods; // increment
}
2.3 改造升级
改造_init函数;并且实现_xhob函数;对data进行处理;重写set和get函数
xhVue.prototype._xhob = function(obj){ // obj = {number:0}
var value;
for(key in obj){
if(obj.hasOwnProperty(ket)){
value = obj[key];
if(typeof value === 'object'){
this._xhob(value);
}
Object.defineProperty(this.$data,key,{
enumerable:true,
configurable:true,
get:function(){
return value;
},
set:function(newVal){
if(value !== newVal){
value = newVal;
}
}
})
}
}
}
xhVue.prototype._init = function(options){
this.$options = options;
this.$el = document.querySelector(options.el);
this.$data = options.data;
this.$method = options.methods;
this._xhob(this.$data);
}
2.4 xhWatcher
指令类watcher;用来绑定更新函数;实现对DOM更新
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实时更新
}
2.5 完善_init和_xhob
继续完善_init和_xhob函数
// 给init的时候增加一个对象来存储model和view的映射关系;也就是我们前面定义的xhWatcher的实例;当model发生变化时;我们会触发其中的指令另其更新;保证了view也同时更新
xhVue.prototype._init = function(options){
this.$options = options;
this.$el = document.querySelector(options.el);
this.$data = options.data;
this.$method = options.methods;
this._binding = {}; // _binding
this._xhob(this.$data);
}
// 通过init出来的_binding
xhVue.prototype._xhob = function(obj){ // obj = {number:0}
var value;
for(key in obj){
if(obj.hasOwnProperty(ket)){
this._binding[key] = {
// _binding = {number:_directives:[]}
_directives = []
}
value = obj[key];
if(typeof value === 'object'){
this._xhob(value);
}
var binding = this._binding[key];
Object.defineProperty(this.$data,key,{
enumerable:true,
configurable:true,
get:function(){
return value;
},
set:function(newVal){
if(value !== newVal){
value = newVal;
// 当number改变时;触发_binding[number]._directives中已绑定的xhWatcher更新
binding._directives.forEach(function(item){
item.update();
});
}
}
})
}
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
