本身动手实践,就会更加深入的理解
此次的主题:实现构造函数 MyVue。
在上一篇文章中,遗留了如下一些问题:javascript
今天,主要解决一件事,实现构造函数 MyVue,并在其原型上添加 render, compiler, update 这三个方法。
html
(首先声明,实际的Vue会有所不一样)vue
new
调用render
函数function MyVue(options) { if (!this instanceof MyVue) { console.error('Vue is a constructor and should be called with the `new` keyword') } // 内部数据用 _ 开头,只读数据用 $ 开头 this._data = options.data; this._el = options.el; // 准备模板与父节点 this.$el = this._template = document.querySelector(this._el); this._parent = this._template.parentNode; // 开始渲染 this.render(); }
其次,在 MyVue 的原型上添加 render 函数,目前尚未杂七杂八的生命周期函数,因此只需编译便可~java
MyVue.prototype.render = function () { this.compiler(); }
最后,在 MyVue 的原型上添加 compiler 函数,内部调用以前写好的编译函数。git
/** 编译,获得真正的DOM */ MyVue.prototype.compiler = function () { let newDOM = this._template.cloneNode(true); compiler(newDOM, this._data); // 这个函数在上一章中写到 this._parent.replaceChild(newDOM, this._template); }
html内代码以下github
<div id="root"> <p>{{name}}</p> <p>{{message}}</p> <p>{{name}} -- {{message}}</p> </div> let app = new MyVue({ el: '#root', data: { name: 'romeo', message: 'handsome but bad guy', } })
效果图:
更多源代码请看个人 github
欢迎关注个人公众号,查看更多系列文章~web