Vue's two-way data binding principle analysis

In the current front-end interview, Vue's two-way data binding has become a very easy test point. Even if you can't write it on the spot, at least you must be able to explain the principle. In this article, I will imitate vue to write an example of two-way data binding, the name is myVue. Combined with the comments, I hope everyone can gain something.

1. Principle The principle of
Vue's two-way data binding is believed to be well understood by everyone. It is mainly achieved by rewriting the set and get functions of data through the defineProperty property of the Object object . Or to achieve an example. In order to make the code clearer, only the most basic content will be implemented here, mainly the three commands v-model, v-bind and v-click, and other commands can also be supplemented by themselves.

Add a picture on the Internet
write picture description here
2. Implementation
The page structure is very simple, as follows:

<div id="app">
    <form>
        <input type="text" v-model="number">
        <button type="button" v-click="increment">增加</button>
    </form>
    <h3 v-bind="number"></h3>
</div> 

Include:

An input, using the v-model directive

A button, using the v-click directive

An h3, using the v-bind directive.

We will finally use our two-way data binding in a vue-like fashion, adding annotations to our data structure:

var app =
new myVue({
    el: '#app',
    data:
    {
        number:0
    },
    methods:
    {
        increment:
        function()
        {
            this.number++;
        },
    }
})

First we need to define a myVue constructor:

function myVue(options){
}

To initialize this constructor, add an _init attribute to it:

function myVue(options){
    this._init(options);
}
myVue.prototype._init =function(options){
    this.$options = options;// options 为上面使用时传入的结构体,包括el,data,methods
    this.$el = document.querySelector(options.el); // el是 #app, this.$el是id为app的Element元素
    this.$data = options.data;// this.$data = {number: 0}
    this.$methods = options.methods; // this.$methods = {increment: function(){}}
}

Next, implement the _obverse function, process the data, and rewrite the set and get functions of the data:

and transform the _init function

Reference URL: https://mp.weixin.qq.com/s/MGsEGejaADVHGlZFYQgCnQ

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326011565&siteId=291194637