Vue 的双向数据绑定原理解析

在目前的前端面试中,vue的双向数据绑定已经成为了一个非常容易考到的点,即使不能当场写出来,至少也要能说出原理。本篇文章中我将会仿照vue写一个双向数据绑定的实例,名字就叫myVue吧。结合注释,希望能让大家有所收获。

1、原理
Vue的双向数据绑定的原理相信大家也都十分了解了,主要是通过 Object对象的defineProperty属性,重写data的set和get函数来实现的,这里对原理不做过多描述,主要还是来实现一个实例。为了使代码更加的清晰,这里只会实现最基本的内容,主要实现v-model,v-bind 和v-click三个命令,其他命令也可以自行补充。

添加网上的一张图
这里写图片描述
2、实现
页面结构很简单,如下:

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

包含:

一个input,使用v-model指令

一个button,使用v-click指令

一个h3,使用v-bind指令。

我们最后会通过类似于vue的方式来使用我们的双向数据绑定,结合我们的数据结构添加注释:

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

首先我们需要定义一个myVue构造函数:

function myVue(options){
}

为了初始化这个构造函数,给它添加一个 _init 属性:

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(){}}
}

接下来实现 _obverse 函数,对data进行处理,重写data的set和get函数:

扫描二维码关注公众号,回复: 198328 查看本文章

并改造_init函数

参考网址:https://mp.weixin.qq.com/s/MGsEGejaADVHGlZFYQgCnQ

猜你喜欢

转载自blog.csdn.net/qq_29132907/article/details/80001642