需要用到 Object.defineProperty
<body>
手写一个简单双向绑定<br />
<input type="text" id="model" /><br />
<div id="modelText"></div>
</body>
<script>
var user = {}
var defaultName = '你好,Vue'
var model = document.querySelector('#model')
var modelText = document.querySelector('#modelText')
model.value = defaultName
modelText.textContent = defaultName
Object.defineProperty(user, 'name', {
get() {
return defaultName
},
set(newValue) {
defaultName = newValue
model.value = newValue
modelText.textContent = newValue
}
})
model.addEventListener(
'keyup',
() => { user.name = model.value },
false
)
</script>