Vue implement the principle of two-way data binding

Vue implement the principle of two-way data binding: Object.defineProperty ()


vue achieve two-way data binding mainly: the use of data in conjunction with hijacking a publisher - way mode subscribers by Object.defineProperty () to hijack each attribute setter, getter, posted a message to subscribers when data changes, trigger the corresponding monitor callback. When the object is passed to a common Javascript Vue instance as its data option, Vue will traverse its properties, they are converted by Object.defineProperty getter / setter. Users do not see getter / setter, but internally they let Vue track dependent, when informed of the changes in the property is accessed and modified.

The two-way data binding vue MVVM data entry as binding, the Observer integration, Watcher Compile and three, to monitor their model data changes by the Observer, compiled template to parse command (vue is used by parsing {Compile {}}), using a watcher finally acts as a bridge between the observer and the Compile, to achieve the data change -> view update; view change interaction (INPUT) -> data model changes way binding effect.

js achieve a simple way binding

<body>
<div id="app">
<input type="text" id="txt">
<p id="show"></p>
</div>
</body>
<script type="text/javascript">
var obj = {}
Object.defineProperty(obj, 'txt', {
get: function () {
return obj
},
set: function (newValue) {
document.getElementById('txt').value = newValue
document.getElementById('show').innerHTML = newValue
}
})
document.addEventListener('keyup', function (e) {
obj.txt = e.target.value
})
</script>

Guess you like

Origin www.cnblogs.com/Su-feng-address/p/12130843.html