-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyvue.js
78 lines (76 loc) · 2.54 KB
/
myvue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Vue extends EventTarget{
constructor(options){
super();
this.$options = options;
this._data = options.data;
this.observer(this._data);
this.compile();
}
observer(data){
for(let key in data){
let value = data[key];
let _this = this;
Object.defineProperty(data,key,{
configurable:true,
enumerable:true,
get(){
console.log("get...");
return value;
},
set(newValue){
console.log("set...");
let event = new CustomEvent(key,{
detail: newValue
});
_this.dispatchEvent(event)
value = newValue;
}
})
}
}
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes;
// console.log(childNodes);
childNodes.forEach(node=>{
// console.log(node);
// 文本 元素节点;
if( node.nodeType ===1){
// 元素节点
if(node.childNodes.length>0){
this.compileNodes(node);
}
}else if(node.nodeType===3){
// 文本
// 匹配 ”{{}}“的文本
let reg = /\{\{\s*([^\{\}\s]+)\s*\}\}/g;
let textContent = node.textContent;
console.log("??",textContent);
if(reg.test(textContent)){
console.log("有大括号表达式");
// 获取数据的下标
// RegExp Function Object
let $1 = RegExp.$1;
// RegExp.$2
// console.log($1);
let rData = this._data[$1];
console.log(rData);
// console.log(this.$options.data);
// 将数据渲染到视图;
node.textContent = node.textContent.replace(reg,rData);
this.addEventListener($1,e=>{
console.log("自定义事件",e.detail);
// 重新渲染模板;获取新值;
let oldValue = this._data[$1];
let newValue = e.detail;
let reg = new RegExp(oldValue);
node.textContent = node.textContent.replace(reg,newValue);
})
}
}
})
}
}