console
class SimpleVue {
constructor(options) {
this.$el = document.querySelector(options.el);
this.$data = options.data;
this.$methods = options.methods;
this.oWatcherObj = {};
this.observe();
this.compile(this.$el);
}
observe() {
for (let key in this.$data) {
let value = this.$data[key];
this.oWatcherObj[key] = [];
let oWatcherObj = this.oWatcherObj[key];
Object.defineProperty(this.$data, key, {
configurable: false,
enumerable: false,
get() {
return value;
},
set(newVal) {
if (newVal !== value) {
value = newVal;
oWatcherObj.forEach((obj) => {
obj.update();
});
}
}
});
}
}
compile(el) {
let nodes = el.children;
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
if (node.children.length > 0) {
this.compile(node);
}
if (node.hasAttribute('yf-on:click')) {
let eventAttrVal = node.getAttribute('yf-on:click');
node.addEventListener('click', this.$methods[eventAttrVal].bind(this.$data));
}
if (node.hasAttribute('yf-if')) {
let ifAttrVal = node.getAttribute('yf-if');
this.oWatcherObj[ifAttrVal].push(new Watcher(this, node, "", ifAttrVal));
}
if (node.hasAttribute('yf-model')) {
let modelAttrVal = node.getAttribute('yf-model');
node.addEventListener('input', ((i) => {
this.oWatcherObj[modelAttrVal].push(new Watcher(this, node, "value", modelAttrVal));
return () => {
this.$data[modelAttrVal] = nodes[i].value;
}
})(i));
}
if (node.hasAttribute('yf-text')) {
let textAttrVal = node.getAttribute('yf-text');
this.oWatcherObj[textAttrVal].push(new Watcher(this, node, "innerText", textAttrVal));
}
}
}
}
<div id="simpleVue">
<button yf-on:click="copy">
戳我
</button>
<div>
<textarea yf-model="name">
</textarea>
<div yf-text="name">
</div>
</div>
<hr>
<button yf-on:click="show">
显示/隐藏
</button>
<div yf-if="isShow">
<input type="text" yf-model="webSite">
<div yf-text="webSite">
</div>
</div>
</div>
<script src="./simpleVue.js"></script>
<script type="text/javascript" >
let vm = new SimpleVue({
el: '#simpleVue',
data: {
name: '苏日俪格',
webSite: 'https://github.com/YuFy1314',
isShow: true
},
methods: {
copy() {
this.name += '苏日俪格';
},
show() {
if (this.isShow) {
this.isShow = false;
} else {
this.isShow = true;
}
}
}
});
</script>