本身動手實踐,就會更加深入的理解
此次的主題:實現構造函數 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