模拟Vue2的v-model
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<!-- <button id="myBtn">改变username</button>-->
<label for="myInput">请输入些什么:</label><input type="text" id="myInput"/>
<h1 id="myTitle"></h1>
</div>
</body>
<script>
let userinfo = {
username: '小明'
}
//初始化时反显变量的值
updateDom(userinfo.username)
// 利用Object.defineProperty监听对象值的变化
watcher();
function watcher() {
Object.defineProperty(userinfo, 'username', {
set(value) {
updateDom(value)
},
get(val) {
return val
}
})
}
// 更新dom数据
function updateDom(value) {
document.querySelector('#myInput').value = value
document.querySelector('#myTitle').innerHTML = value
}
// 给input绑定input事件,实时修改username的值
document.querySelector('#myInput').oninput = function (e) {
let value = e.target.value
userinfo.username = value
}
//
// document.querySelector('#myBtn').onclick = function () {
// let value = '小红'
// userinfo.username = value
// }
</script>
</html>
运行效果:
标签:username,function,querySelector,value,userinfo,Vue2,model,document,模拟 From: https://www.cnblogs.com/ma1998/p/17621893.html