美文网首页
JavaScript模拟Vue.js有生命周期的效果

JavaScript模拟Vue.js有生命周期的效果

作者: Eirmood | 来源:发表于2023-06-20 10:23 被阅读0次
    image.png

    deepVue.js:

    function Vue(options) {
    this.$options = options;

    if (typeof options.beforeCreate === 'function') {
    options.beforeCreate.call(this);
    }

    this._data = typeof options.data === 'function' ? options.data() : options.data;

    this._proxyData();

    if (typeof options.created === 'function') {
    options.created.call(this);
    }

    this.$mount(options.el);
    }

    Vue.prototype.mount = function(el) { this.el = document.querySelector(el);

    if (typeof this.options.beforeMount === 'function') { this.options.beforeMount.call(this);
    }

    this.render();

    if (typeof this.options.mounted === 'function') { this.options.mounted.call(this);
    }
    };

    Vue.prototype._proxyData = function() {
    var self = this;
    Object.keys(this._data).forEach(function(key) {
    Object.defineProperty(self, key, {
    get: function() {
    return self._data[key];
    },
    set: function(newValue) {
    self._data[key] = newValue;
    if (typeof self.options.beforeUpdate === 'function') { self.options.beforeUpdate.call(self);
    }
    self.render();
    if (typeof self.options.updated === 'function') { self.options.updated.call(self);
    }
    }
    });
    });
    };

    Vue.prototype.render = function() {
    if (typeof this.options.render === 'function') { this.el.innerHTML = this.$options.render.call(this);
    }
    };

    var app = new Vue({
    el: '#airmood',
    data: {
    message: 'Hello, airmood!'
    },
    beforeCreate: function() {
    console.log('beforeCreate airmood');
    },
    created: function() {
    console.log('created airmood');
    },
    beforeMount: function() {
    console.log('beforeMount airmood');
    },
    mounted: function() {
    console.log('mounted airmood');
    },
    beforeUpdate: function() {
    console.log('beforeUpdate airmood');
    },
    updated: function() {
    console.log('updated airmood');
    },
    render: function() {
    return '<h2>' + this.message + '</h2>';
    }
    });

    deepVue.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>deepVue</title>
    </head>
    <body>
    <div id="airmood"></div>
    <script src="./deepVue.js"></script>
    </body>
    </html>

    相关文章

      网友评论

          本文标题:JavaScript模拟Vue.js有生命周期的效果

          本文链接:https://www.haomeiwen.com/subject/vuyyydtx.html