image.png
一個(gè)input袱耽,一個(gè)按鈕死遭,一個(gè)顯示值鞠眉,把大象裝冰箱,總共分三步:
(1) 一個(gè)input,用v-model指令實(shí)現(xiàn)雙向數(shù)據(jù)綁定(1.改變number數(shù)據(jù),template input框值跟著變嫉沽。2.input框值改變辟犀,number數(shù)據(jù)變)
(2) 一個(gè)button,用v-on:click 實(shí)現(xiàn)綁定事件(解析指令,綁定click監(jiān)聽事件)
(3) 一個(gè)h3绸硕,用v-bind和 {{ }} 實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)監(jiān)聽(引用number的template都跟著改變)
<html>
<div id="app">
<form>
<input type="text" v-model="number">
<button type="button" v-on:click="increment">增加</button>
</form>
<h3 v-bind:title="number">{{number}}</h3>
</div>
<script>
// 我理解當(dāng)存儲(chǔ)容器了 key是data的每個(gè)屬性, value是_directives數(shù)組
// 放著 complie dom后的依賴屬性的每個(gè)節(jié)點(diǎn)信息, 用來監(jiān)聽set屬性值改變后, 更新dom節(jié)點(diǎn)值
var _binding = {};
this.init();
// 初始化
function init() {
// data
this.obj = {
number: 0
};
this.observe();
this.complie(document.querySelector("#app"));
};
/*
* _observe方法劫持data對(duì)象里的屬性, 每個(gè)屬性重寫set方法, 這個(gè)屬性值改變時(shí)候觸發(fā)set方法,
* 去_binding里找這個(gè)屬性key,更新complie時(shí)訂閱的dom節(jié)點(diǎn)值
*/
function observe() {
_this = this;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(this._binding)
this._binding[key]= {
_directives : []
}
value = obj[key];
// 劫持get堂竟、set方法
Object.defineProperty(obj, key, {
get: function () {
console.log('get被調(diào)用');
return value;
},
set: function (newValue) {
console.log('set被調(diào)用,newValue:' + newValue);
value = newValue;
// 通知訂閱者 改變節(jié)點(diǎn)
console.log(_this._binding);
if (_this._binding[key]) {
_this._binding[key]._directives.forEach(dir => {
[dir.el][0][dir.attr] = value;
});
}
}
})
}
};
}
/**
* complie解析模板DOM指令 放入_binding 訂閱依賴
* (就是哪塊dom依賴哪個(gè)值,key value 形式存進(jìn)放入_binding{}里)
*/
function complie(root) {
let _this = this;
let nodes = root.children;
console.log(nodes);
for (let index = 0; index < nodes.length; index++) {
const element = nodes[index];
console.log(element)
if (element.children.length) {
this.complie(element);
}
// 解析v-on:click
if (element.hasAttribute('v-on:click')) {
console.log('hasAttribute:v-on:click')
element.addEventListener('click', function () {
console.log('click');
_this.increment();
}, false)
}
// 解析v-model
if (element.hasAttribute('v-model')) {
console.log('hasAttribute:v-model');
let attrVal = element.getAttribute('v-model');
// 監(jiān)聽input框輸入值時(shí) 改變屬性值
element.addEventListener('input', function(key) {
console.log('監(jiān)聽input值:' + element.value);
_this.obj[attrVal] = element.value;
})
this._binding[attrVal]._directives.push({el: element, attr: 'value', _this: _this});
}
// 解析innerHtml,替換{{}}里面的數(shù)據(jù)
if (element.innerHTML) {
console.log('innerHtml: {{}}');
console.log(element.innerHTML);
let innerHTMLStr = element.innerHTML;
var matchReg = /(?<={{).*?(?=})/g;
if (innerHTMLStr.match(matchReg)) {
for (let attrVal of innerHTMLStr.match(matchReg)) {
this._binding[attrVal]._directives.push({ el: element, attr: 'innerHTML', _this: _this });
}
}
}
}
}
function increment() {
obj.number++;
}
</script>
</html>