7

我们新建一个 smallVue.js 文件,内容如下:

function Vue(options){

    this.beforeMount = options.beforeMount;

    this.el = document.getElementById(options.el);

    this.view = "";

    this.data = options.data;

    this.template = options.template;

    this.methods = options.methods;

    this.init();

}

// 初始化
Vue.prototype.init = function(){

    this.obseverData();
    this.render();
    this.bindEvent();

}

// 数据绑定
Vue.prototype.obseverData = function(){

    // 为每个数据进行数据绑定 ,在数据修改时会发生页面刷新
    var vm = this;

    var data = this.data;

    for ( var key in data ) {
    
        Object.defineProperty(vm,key,{
            set:function(val){
                vm.data[key] = val;
                vm.render();
                vm.bindEvent();
                // console.log(vm.data[key]);
            },
            get:function(){
                return vm.data[key];
            }
        })

    }


}

// 视图渲染
Vue.prototype.render = function(){


    var vm = this;
    vm.view = vm.template.replace(/\{\{(\w+)\}\}/g,function(str,code){

        return vm[code];
    });


    // beforeMount生命钩子
    vm.beforeMount();

    vm.mount();

}



// 事件绑定
Vue.prototype.bindEvent = function(){

    var vm  = this;
    var doms = document.querySelectorAll('[v-on]');

    for (var i = 0; i < doms.length; i++) {
        var dom = doms[i];

        var vOn = dom.getAttribute('v-on');  //click:showName

        var eventName = vOn.split(':')[0];
        var methodName = vOn.split(':')[1];


        dom.addEventListener(eventName,function(){
            vm.methods[methodName].apply(vm)
        })
    }

}

// 挂载
Vue.prototype.mount = function(){


    this.el.innerHTML = this.view;


}

然后再新建一个test.html文件,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!-- <canvas id="canvas"></canvas> -->

    <div id="view"></div>

    <script src="./smallVue.js">
    </script>

    <script>
        
        var vue = new Vue({
            el:'view',
            data:{
                name:'jack'
            },
            methods:{
                showName:function(){
                    console.log(this.name);
                }
            },
            template:"<div   v-on='click:showName'>{{name}}</div>",
            beforeMount:function(){
                console.log('beforeMount')
            }
        })

    </script>


</body>
</html>

大家可以运行试一下


豆豆
111 声望5 粉丝

« 上一篇
Vuex 源码分析