vue底层原理之双向数据绑定,用js简单实现
//html
<input id="one" type="text" placeholder="请输入值">
<p>
当前输入的值:
<span id="two">--</span>
</p>
//js
var oOne = document.getElementById('one');
var oTwo = document.getElementById('two');
var newValue = {};
Object.defineProperty(newValue, 'msg', {
// 设置 obj.msg 当obj.msg反生改变时set方法将会被调用
set: function (newVal) {
// 当obj.msg被赋值时 同时设置给 input/span
oOne.value = newVal
oTwo.innerText = newVal
}
});
oOne.addEventListener('keyup', function (event) {
newValue.msg = event.target.value
})