仿Vue原理寫的例子,初步解析Vue原理

咱們新建一個 smallVue.js 文件,內容以下:html

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文件,內容以下:vue

<!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>

你們能夠運行試一下canvas

相關文章
相關標籤/搜索