标题: 30行JS代码搞定前端双向数据绑定,最简版本
时间: 2023-10-03
<input type="number" type="text" bind-data="text1" />
<p bind-data="text1">默认值</p>
<script>
....,
//使用js动态修改,对应字段会自动更新
data.text1= '123';//新值
....,
</script>
<div>单价:<input type="number" type="text" bind-data="price" /></div>
<div>数量:<input type="number" type="text" bind-data="quantity" /></div>
<div>总价:<span bind-fun="totalPrice">0</span></div>
<script>
function totalPrice(){
//this指向数据对象
return this.price * this.quantity;
}
</script>
let data = new Proxy({}, {
set(obj, key, value) {
obj[key] = value;
const dataElements = document.querySelectorAll(`[bind-data="${key}"]`);
const funcElements = document.querySelectorAll("[bind-fun]");
dataElements.forEach((element) => {
element instanceof HTMLInputElement ? (element.value = value) : (element.innerText = value);
});
if (funcElements.length > 0) {
funcElements.forEach((element) => {
const funcName = element.getAttribute("bind-fun");
if (typeof window[funcName] !== "function") return;
const func = window[funcName].bind(obj);
const val = func() || "";
element instanceof HTMLInputElement ? (element.value = val) : (element.innerText = val);
});
}
return true;
},
get(obj, key) {
return obj[key];
},
});
document.addEventListener("input", function (event) {
if (!event.target.hasAttribute("bind-data")) return;
data[event.target.getAttribute("bind-data")] = event.target.value;
});
『回复列表(3|隐藏机器人聊天)』