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

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


var app = new xhVue({
el:'#app',
data: {
number: 0
},
methods: {
increment: function() {
this.number ++;
},
}
})

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也同时更新