####(4)输入框数据绑定
bindInput(el){
//获取input所有元素节点
const _allInput = el.querySelectorAll('input');
_allInput.forEach(input => {
const _vModel = input.getAttribute('v-model');
//判断是否有v-model属性
if(_vModel){
//监听输入事件 input.addEventListener('keyup',this.handleInput.bind(this,_vModel,input),false);
}
})
}
handleInput(key,input){
const _value = input.value;
//数据变化的时候会同步修改dom节点绑定的数据。
this.data[key] = _value;
}
(4)完整代码
class VModel {
constructor(el,data) {
this.el = document.querySelector(el);
this._data = data;
this.domPoll = {};
this.init();
}
init(){
this.initData();
this.initDom();
}
initDom(){
this.bindDom(this.el);
this.bindInput(this.el);
console.log('domPoll',this.domPoll);
}
initData () {
const _this = this;
this.data = {};
// for(let key in this._data){
// Object.defineProperty(this.data,key,{
// get(){
// console.log("获取数据",key,_this._data[key]);
// return _this._data[key];
// },
// set(newVal){
// console.log("设置数据",key,newVal);
// _this.domPoll[key].innerText = newVal;
// _this._data[key] = newVal;
// }
// });
// }
this.data = new Proxy(this.data,{
get(target,key){
return Reflect.get(target,key);
},
set(target,key,value){
// _this.domPoll[key].innerText = value;
_this.domPoll[key].forEach(item => {
item.innerText = value;
})
return Reflect.set(target,key,value);
}
})
}
bindDom(el){
const childNodes = el.childNodes;
childNodes.forEach(item => {
if(item.nodeType === 3){
const _value = item.nodeValue;
if(_value.trim().length){
let _isValid = /{{(.+?)}}/.test(_value);
if(_isValid){
const _key = _value.match(/{{(.+?)}}/)[1].trim();
// this.domPoll[_key] = item.parentNode;
if(!this.domPoll[_key]) this.domPoll[_key] = [];
this.domPoll[_key].push(item.parentNode);
item.parentNode.innerText = this.data[_key] || undefined;
}
}
}
item.childNodes && this.bindDom(item);
})
}
bindInput(el){
const _allInput = el.querySelectorAll('input');
_allInput.forEach(input => {
const _vModel = input.getAttribute('v-model');
if(_vModel){
input.addEventListener('keyup',this.handleInput.bind(this,_vModel,input),false);
}
})
}
handleInput(key,input){
const _value = input.value;
this.data[key] = _value;
// console.log(this.data);
}
setData(key,value){
this.data[key] = value;
}
}