雙向資料繫結的實現
阿新 • • 發佈:2020-12-22
技術標籤:jsjavascript
<body>
<input type="text" v-model="title" />
<input type="text" v-model="title" />
<input type="text" v-model="title" />
<h4 v-bind="title">這裡也會發生更新</h4>
</body>
<script>
function View() {
let proxy = new Proxy({}, {
get(obj, property) {},
set(obj, property, value) {
document.querySelectorAll(`[v-model="${property}"]`).forEach(item => {
item.value = value;
});
document.querySelectorAll( `[v-bind="${property}"]`).forEach(item => {
item.innerHTML = value;
})
}
});
this.init = function() {
const els = document.querySelectorAll("[v-model]");
els.forEach(item => {
item.addEventListener("keyup", function () {
proxy[this.getAttribute('v-model')] = this.value
});
});
};
}
new View().init();