javascript - Is Vue's dependency tracking one-way data binding or two-way binding?
大家讲道理
大家讲道理 2017-07-05 10:53:36
0
1
828

As mentioned in the official website documentation, Vue's v-model directive implements two-way binding of data.

https://vuejs.org/v2/guide/fo...

However, in actual development, the data flow of components is one-way, and it is not recommended for sub-components to modify the props of parent components.

So the question is, is Vue's dependency tracking [supports two-way binding in principle, but only recommends one-way data flow for development convenience], or [does not support two-way binding in principle, What about v-model which is just syntax sugar implemented by listening to DOM events?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
大家讲道理

Vue’s dependency tracking is [in principle, two-way binding is not supported, v-model is just syntax sugar implemented by listening to DOM events]

Vue’s dependency tracking is implemented by converting all the properties of the data object into getters/setters through Object.defineProperty; when a certain property value of the data is changed, the set function will be triggered, and when the property value is obtained, the get function will be triggered. , through this feature, the view can be changed when the data is changed; that is to say, the change of the view will be triggered only when the data changes. Conversely, when the view is operated, the data can only be changed through DOM events, and then the view can be changed. This is used to achieve two-way binding

The general process is as follows

    //data
    var obj = {
        'message':'hello'
    }

    //vm
    var val = obj.message
    Object.defineProperty(obj,'message',{
        get(){
            return val
        },
        set(value){
            val = value
            updataView()
        }
    })

    function updataView(){
        box.innerHTML = obj.message //触发get
    }

    // init
    updataView()

    textIpt.oninput = function(){
        obj.message = this.value //触发set
    }

Two-way binding is to bind data and views within the same component, and has nothing to do with the communication between parent and child components;
The communication between components uses one-way data flow for better understanding between components. Coupling. During development, there may be multiple sub-components that depend on certain data of the parent component. If the sub-component can modify the data of the parent component, a change in the sub-component will cause changes in all sub-components that rely on this data, so Vue does not recommend sub-components. If the component modifies the data of the parent component, directly modifying the props will throw a warning

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template