從零手寫 Vue 之虛擬 do
這篇文章主要是按照 Vue2
源碼的目錄格式和調用過程,把我們之前寫的虛擬 dom
代碼位置整理一下。
相比於 從零手寫 Vue 之響應式系統,這次還新建了 code/VueLiang1/src/platforms/web
目錄,將和 web
相關的操作都放到了該目錄中,並且把 Vue
的入口文件換爲平臺相關的 code/VueLiang1/src/platforms/web/entry-runtime.js
。
這次的測試文件就已經非常有 Vue
那味兒了。
import Vue from "./src/platforms/web/entry-runtime";
new Vue({
el: "#root",
data() {
return {
test: 1,
name: "data:liang",
};
},
watch: {
test(newVal, oldVal) {
console.log(newVal, oldVal);
},
},
computed: {
text() {
return "computed:hello:" + this.name;
},
},
methods: {
hello() {
console.log("調用methods:hello");
return "調用methods:hello";
},
click() {
this.test = 3;
this.name = "wind";
},
},
render(createElement) {
const test = createElement(
"div",
{
on: {
click: () => this.click(),
dblclick: () => this.hello(),
},
},
[this.text, createElement("div", this.test)]
);
return test;
},
});
我們實現了核心的響應式系統,還有之前的 watch
和 computed
, render
函數可以直接通過 createElement
來生成虛擬 dom
。看一下效果:
關於虛擬 dom
還剩下自定義組件沒有實現,下篇文章會在今天完成的 code/VueLiang1
的代碼下來實現,大家也可以先調試熟悉一下。
虛擬 dom
介紹完之後,下一個大篇章就會介紹「模版編譯」了,也就是寫 template
模版,然後自動編譯爲虛擬 dom
,歡迎持續關注。
每篇文章的源碼都可以在 github 上找到並且運行,覺得不錯的話也感謝 star
。
https://github.com/wind-liang/vue2
windliang 前端,生活,成長
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/oO4aEkPx35xompLqlGqE6A