Vue3.5中響應式Props解構的編譯原理
前言
在Vue3.5版本中響應式 Props 解構終于正式轉正了,這個功能之前一直是試驗性的。這篇文章來帶你搞清楚,一個String類型的props經過解構后明明應該是一個常量了,為什么還沒丟失響應式呢?本文中使用的Vue版本為歐陽寫文章時的最新版Vue3.5.5
看個demo
我們先來看個解構props的例子。
父組件代碼如下:
<template> <ChildDemo name="ouyang" /> </template> <script setup lang="ts"> import ChildDemo from "./child.vue"; </script>
父組件代碼很簡單,給子組件傳了一個名為name的prop,name的值為字符串“ouyang”。
子組件的代碼如下:
<template>
{{ localName }}
</template>
<script setup lang="ts">
const { name: localName } = defineProps(["name"]);
console.log(localName);
</script>
在子組件中我們將name給解構出來了并且賦值給了localName,講道理解構出來的localName應該是個常量會丟失響應式的,其實不會丟失。
我們在瀏覽器中來看一下編譯后的子組件代碼,很簡單,直接在network中過濾子組件的名稱即可,如下圖:
從上面可以看到原本的console.log(localName)經過編譯后就變成了console.log(__props.name),這樣當然就不會丟失響應式了。
我們再來看一個另外一種方式解構的例子,這種例子解構后就會丟失響應式,子組件代碼如下:
<template>
{{ localName }}
</template>
<script setup lang="ts">
const props = defineProps(["name"]);
const { name: localName } = props;
console.log(localName);
</script>
在上面的例子中我們不是直接解構defineProps的返回值,而是將返回值賦值給props對象,然后再去解構props對象拿到localName。
從上圖中可以看到這種寫法使用解構的localName時,就不會在編譯階段將其替換為__props.name,這樣的話localName就確實是一個普通的常量了,當然會丟失響應式。
這是為什么呢?為什么這種解構寫法就會丟失響應式呢?別著急,我接下來的文章會講。
從哪里開下手?
既然這個是在編譯時將localName處理成__props.name,那我們當然是在編譯時debug了。
還是一樣的套路,我們在vscode中啟動一個debug終端。
在之前的 通過debug搞清楚.vue文件怎么變成.js文件文章中我們已經知道了vue文件中的<script>模塊實際是由vue/compiler-sfc包的compileScript函數(shù)處理的。
compileScript函數(shù)位置在/node_modules/@vue/compiler-sfc/dist/compiler-sfc.cjs.js
找到compileScript函數(shù)就可以給他打一個斷點了。
compileScript函數(shù)
在debug終端上面執(zhí)行yarn dev后在瀏覽器中打開對應的頁面,比如: http://localhost:5173/ 。此時斷點就會走到compileScript函數(shù)中。
在我們這個場景中簡化后的compileScript函數(shù)代碼如下:
function compileScript(sfc, options) {
const ctx = new ScriptCompileContext(sfc, options);
const scriptSetupAst = ctx.scriptSetupAst;
// 2.2 process <script setup> body
for (const node of scriptSetupAst.body) {
if (node.type === "VariableDeclaration" && !node.declare) {
const total = node.declarations.length;
for (let i = 0; i < total; i++) {
const decl = node.declarations[i];
const init = decl.init;
if (init) {
// defineProps
const isDefineProps = processDefineProps(ctx, init, decl.id);
}
}
}
}
// 3 props destructure transform
if (ctx.propsDestructureDecl) {
transformDestructuredProps(ctx);
}
return {
//....
content: ctx.s.toString(),
};
}
入參sfc對象:是一個descriptor對象,descriptor對象是由vue文件編譯來的。descriptor對象擁有template屬性、scriptSetup屬性、style屬性,分別對應vue文件的<template>模塊、<script setup>模塊、<style>模塊。
ctx上下文對象:這個ctx對象貫穿了整個script模塊的處理過程,他是根據(jù)vue文件的源代碼初始化出來的。在compileScript函數(shù)中處理script模塊中的內容,實際就是對ctx對象進行操作。最終ctx.s.toString()就是返回script模塊經過編譯后返回的js代碼。
搞清楚了入參sfc對象和ctx上下文對象,我們接著來看ctx.scriptSetupAst。從名字我想你也能猜到,他就是script模塊中的代碼對應的AST抽象語法樹。如下圖:
從上圖中可以看到body屬性是一個數(shù)組,分別對應的是源代碼中的兩行代碼。
數(shù)組的第一項對應的Node節(jié)點類型是VariableDeclaration,他是一個變量聲明類型的節(jié)點。對應的就是源代碼中的第一行:const { name: localName } = defineProps(["name"])
數(shù)組中的第二項對應的Node節(jié)點類型是ExpressionStatement,他是一個表達式類型的節(jié)點。對應的就是源代碼中的第二行:console.log(localName)
我們接著來看compileScript函數(shù)中的外層for循環(huán),也就是遍歷前面講的body數(shù)組,代碼如下:
function compileScript(sfc, options) {
// ...省略
// 2.2 process <script setup> body
for (const node of scriptSetupAst.body) {
if (node.type === "VariableDeclaration" && !node.declare) {
const total = node.declarations.length;
for (let i = 0; i < total; i++) {
const decl = node.declarations[i];
const init = decl.init;
if (init) {
// defineProps
const isDefineProps = processDefineProps(ctx, init, decl.id);
}
}
}
}
// ...省略
}我們接著來看外層for循環(huán)里面的第一個if語句:
if (node.type === "VariableDeclaration" && !node.declare)
這個if語句的意思是判斷當前的節(jié)點類型是不是變量聲明并且確實有初始化的值。
我們這里的源代碼第一行代碼如下:
const { name: localName } = defineProps(["name"]);很明顯我們這里是滿足這個if條件的。
接著在if里面還有一個內層for循環(huán),這個for循環(huán)是在遍歷node節(jié)點的declarations屬性,這個屬性是一個數(shù)組。
declarations數(shù)組屬性表示當前變量聲明語句中定義的所有變量,可能會定義多個變量,所以他才是一個數(shù)組。在我們這里只定義了一個變量localName,所以 declarations數(shù)組中只有一項。
在內層for循環(huán),會去遍歷聲明的變量,然后從變量的節(jié)點中取出init屬性。我想聰明的你從名字應該就可以看出來init屬性的作用是什么。
沒錯,init屬性就是對應的變量的初始化值。在我們這里聲明的localName變量的初始化值就是defineProps(["name"])函數(shù)的返回值。
接著就是判斷init是否存在,也就是判斷變量是否是有初始化值。如果為真,那么就執(zhí)行processDefineProps(ctx, init, decl.id)判斷初始化值是否是在調用defineProps。換句話說就是判斷當前的變量聲明是否是在調用defineProps宏函數(shù)。
processDefineProps函數(shù)
接著將斷點走進processDefineProps函數(shù),在我們這個場景中簡化后的代碼如下:
function processDefineProps(ctx, node, declId) {
if (!isCallOf(node, DEFINE_PROPS)) {
return processWithDefaults(ctx, node, declId);
}
// handle props destructure
if (declId && declId.type === "ObjectPattern") {
processPropsDestructure(ctx, declId);
}
return true;
}processDefineProps函數(shù)接收3個參數(shù)。
第一個參數(shù)ctx,表示當前上下文對象。
第二個參數(shù)node,這個節(jié)點對應的是變量聲明語句中的初始化值的部分。也就是源代碼中的defineProps(["name"])。
第三個參數(shù)declId,這個對應的是變量聲明語句中的變量名稱。也就是源代碼中的{ name: localName }。
在 為什么defineProps宏函數(shù)不需要從vue中import導入?文章中我們已經講過了這里的第一個if語句就是用于判斷當前是否在執(zhí)行defineProps函數(shù),如果不是那么就直接return false
我們接著來看第二個if語句,這個if語句就是判斷當前變量聲明是不是“對象解構賦值”。很明顯我們這里就是解構出的localName變量,所以代碼將會走到processPropsDestructure函數(shù)中。
processPropsDestructure函數(shù)
接著將斷點走進processPropsDestructure函數(shù),在我們這個場景中簡化后的代碼如下:
function processPropsDestructure(ctx, declId) {
const registerBinding = (
key: string,
local: string,
defaultValue?: Expression
) => {
ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
};
for (const prop of declId.properties) {
const propKey = resolveObjectKey(prop.key);
registerBinding(propKey, prop.value.name);
}
}前面講過了這里的兩個入參,ctx表示當前上下文對象。declId表示變量聲明語句中的變量名稱。
首先定義了一個名為registerBinding的箭頭函數(shù)。
接著就是使用for循環(huán)遍歷declId.properties變量名稱,為什么會有多個變量名稱呢?
答案是解構的時候我們可以解構一個對象的多個屬性,用于定義多個變量。
prop屬性如下圖:
從上圖可以看到prop中有兩個屬性很顯眼,分別是key和value。
其中key屬性對應的是解構對象時從對象中要提取出的屬性名,因為我們這里是解構的name屬性,所以上面的值是name。
其中value屬性對應的是解構對象時要賦給的目標變量名稱。我們這里是賦值給變量localName,所以上面他的值是localName。
接著來看for循環(huán)中的代碼。
執(zhí)行const propKey = resolveObjectKey(prop.key)拿到要從props對象中解構出的屬性名稱。
將斷點走進resolveObjectKey函數(shù),代碼如下:
function resolveObjectKey(node: Node) {
switch (node.type) {
case "Identifier":
return node.name;
}
return undefined;
}如果當前是標識符節(jié)點,也就是有name屬性。那么就返回name屬性。
最后就是執(zhí)行registerBinding函數(shù)。
registerBinding(propKey, prop.value.name)
第一個參數(shù)為傳入解構對象時要提取出的屬性名稱,也就是name。第二個參數(shù)為解構對象時要賦給的目標變量名稱,也就是localName。
接著將斷點走進registerBinding函數(shù),他就在processPropsDestructure函數(shù)里面。
function processPropsDestructure(ctx, declId) {
const registerBinding = (
key: string,
local: string,
defaultValue?: Expression
) => {
ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
};
// ...省略
}ctx.propsDestructuredBindings是存在ctx上下文中的一個屬性對象,這個對象里面存的是需要解構的多個props。
對象的key就是需要解構的props。
key對應的value也是一個對象,這個對象中有兩個字段。其中的local屬性是解構props后要賦給的變量名稱。default屬性是props的默認值。
在debug終端來看看此時的ctx.propsDestructuredBindings對象是什么樣的,如下圖:
從上圖中就有看到此時里面已經存了一個name屬性,表示props中的name需要解構,解構出來的變量名為localName,并且默認值為undefined。
經過這里的處理后在ctx上下文對象中的ctx.propsDestructuredBindings中就已經存了有哪些props需要解構,以及解構后要賦值給哪個變量。
有了這個后,后續(xù)只需要將script模塊中的所有代碼遍歷一次,然后找出哪些在使用的變量是props解構的變量,比如這里的localName變量將其替換成__props.name即可。
transformDestructuredProps函數(shù)
接著將斷點層層返回,走到最外面的compileScript函數(shù)中。再來回憶一下compileScript函數(shù)的代碼,如下:
function compileScript(sfc, options) {
const ctx = new ScriptCompileContext(sfc, options);
const scriptSetupAst = ctx.scriptSetupAst;
// 2.2 process <script setup> body
for (const node of scriptSetupAst.body) {
if (node.type === "VariableDeclaration" && !node.declare) {
const total = node.declarations.length;
for (let i = 0; i < total; i++) {
const decl = node.declarations[i];
const init = decl.init;
if (init) {
// defineProps
const isDefineProps = processDefineProps(ctx, init, decl.id);
}
}
}
}
// 3 props destructure transform
if (ctx.propsDestructureDecl) {
transformDestructuredProps(ctx);
}
return {
//....
content: ctx.s.toString(),
};
}
經過processDefineProps函數(shù)的處理后,ctx.propsDestructureDecl對象中已經存了有哪些變量是由props解構出來的。
這里的if (ctx.propsDestructureDecl)條件當然滿足,所以代碼會走到transformDestructuredProps函數(shù)中。
接著將斷點走進transformDestructuredProps函數(shù)中,在我們這個場景中簡化后的transformDestructuredProps函數(shù)代碼如下:
import { walk } from 'estree-walker'
function transformDestructuredProps(ctx) {
const rootScope = {};
let currentScope = rootScope;
const propsLocalToPublicMap: Record<string, string> = Object.create(null);
const ast = ctx.scriptSetupAst;
for (const key in ctx.propsDestructuredBindings) {
const { local } = ctx.propsDestructuredBindings[key];
rootScope[local] = true;
propsLocalToPublicMap[local] = key;
}
walk(ast, {
enter(node: Node) {
if (node.type === "Identifier") {
if (currentScope[node.name]) {
rewriteId(node);
}
}
},
});
function rewriteId(id: Identifier) {
// x --> __props.x
ctx.s.overwrite(
id.start! + ctx.startOffset!,
id.end! + ctx.startOffset!,
genPropsAccessExp(propsLocalToPublicMap[id.name])
);
}
}
在transformDestructuredProps函數(shù)中主要分為三塊代碼,分別是for循環(huán)、執(zhí)行walk函數(shù)、定義rewriteId函數(shù)。
我們先來看第一個for循環(huán),他是遍歷ctx.propsDestructuredBindings對象。前面我們講過了這個對象中存的屬性key是解構了哪些props,比如這里就是解構了name這個props。
接著就是使用const { local } = ctx.propsDestructuredBindings[key]拿到解構的props在子組件中賦值給了哪個變量,我們這里是解構出來后賦給了localName變量,所以這里的local的值為字符串"localName"。
由于在我們這個demo中只有兩行代碼,分別是解構props和console.log。沒有其他的函數(shù),所以這里的作用域只有一個。也就是說rootScope始終等于currentScope。
所以這里執(zhí)行rootScope[local] = true后,currentScope對象中的localName屬性也會被賦值true。如下圖:
接著就是執(zhí)行propsLocalToPublicMap[local] = key,這里的local存的是解構props后賦值給子組件中的變量名稱,key為解構了哪個props。經過這行代碼的處理后我們就形成了一個映射,后續(xù)根據(jù)這個映射就能輕松的將script模塊中使用解構后的localName的地方替換為__props.name。
propsLocalToPublicMap對象如下圖:
經過這個for循環(huán)的處理后,我們已經知道了有哪些變量其實是經過props解構來的,以及這些解構得到的變量和props的映射關系。
接下來就是使用walk函數(shù)去遞歸遍歷script模塊中的所有代碼,這個遞歸遍歷就是遍歷script模塊對應的AST抽象語法樹。
在這里是使用的walk函數(shù)來自于第三方庫estree-walker。
在遍歷語法樹中的某個節(jié)點時,進入的時候會觸發(fā)一次enter回調,出去的時候會觸發(fā)一次leave回調。
walk函數(shù)的執(zhí)行代碼如下:
walk(ast, {
enter(node: Node) {
if (node.type === "Identifier") {
if (currentScope[node.name]) {
rewriteId(node);
}
}
},
});我們這個場景中只需要enter進入的回調就行了。
在enter回調中使用外層if判斷當前節(jié)點的類型是不是Identifier,Identifier類型可能是變量名、函數(shù)名等。
我們源代碼中的console.log(localName)中的localName就是一個變量名,當遞歸遍歷AST抽象語法樹遍歷到這里的localName對應的節(jié)點時就會滿足外層的if條件。
在debug終端來看看此時滿足外層if條件的node節(jié)點,如下圖:
從上面的代碼可以看到此時的node節(jié)點中對應的變量名為localName。其中start和end分別表示localName變量的開始位置和結束位置。
我們回憶一下前面講過了currentScope對象中就是存的是有哪些本地的變量是通過props解構得到的,這里的localName變量當然是通過props解構得到的,滿足里層的if條件判斷。
最后代碼會走進rewriteId函數(shù)中,將斷點走進rewriteId函數(shù)中,簡化后的代碼如下:
function rewriteId(id: Identifier) {
// x --> __props.x
ctx.s.overwrite(
id.start + ctx.startOffset,
id.end + ctx.startOffset,
genPropsAccessExp(propsLocalToPublicMap[id.name])
);
}這里使用了ctx.s.overwrite方法,這個方法接收三個參數(shù)。
第一個參數(shù)是:開始位置,對應的是變量localName在源碼中的開始位置。
第二個參數(shù)是:結束位置,對應的是變量localName在源碼中的結束位置。
第三個參數(shù)是想要替換成的新內容。
第三個參數(shù)是由genPropsAccessExp函數(shù)返回的,執(zhí)行這個函數(shù)時傳入的是propsLocalToPublicMap[id.name]。
前面講過了propsLocalToPublicMap存的是props名稱和解構到本地的變量名稱的映射關系,id.name是解構到本地的變量名稱。如下圖:
所以propsLocalToPublicMap[id.name]的執(zhí)行結果就是name,也就是名為name的props。
接著將斷點走進genPropsAccessExp函數(shù),簡化后的代碼如下:
const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
function genPropsAccessExp(name: string): string {
return identRE.test(name)
? `__props.${name}`
: `__props[${JSON.stringify(name)}]`;
}使用正則表達式去判斷如果滿足條件就會返回__props.${name},否則就是返回__props[${JSON.stringify(name)}]。
很明顯我們這里的name當然滿足條件,所以genPropsAccessExp函數(shù)會返回__props.name。
那么什么情況下不會滿足條件呢?
比如這樣的props:
const { "first-name": firstName } = defineProps(["first-name"]);console.log(firstName);這種props在這種情況下就會返回__props["first-name"]
執(zhí)行完genPropsAccessExp函數(shù)后回到ctx.s.overwrite方法的地方,此時我們已經知道了第三個參數(shù)的值為__props.name。這個方法的執(zhí)行會將localName重寫為__props.name
在ctx.s.overwrite方法執(zhí)行之前我們來看看此時的script模塊中的js代碼是什么樣的,如下圖:
從上圖中可以看到此時的代碼中console.log里面還是localName。
執(zhí)行完ctx.s.overwrite方法后,我們來看看此時是什么樣的,如下圖:
從上圖中可以看到此時的代碼中console.log里面已經變成了__props.name。
這就是在編譯階段將使用到的解構localName變量變成__props.name的完整過程。
這會兒我們來看前面那個例子解構后丟失響應式的例子,我想你就很容易想通了。
<script setup lang="ts">
const props = defineProps(["name"]);
const { name: localName } = props;
console.log(localName);
</script>在處理defineProps宏函數(shù)時,發(fā)現(xiàn)是直接解構了返回值才會進行處理。上面這個例子中沒有直接進行解構,而是將其賦值給props,然后再去解構props。這種情況下ctx.propsDestructuredBindings對象中什么都沒有。
后續(xù)在遞歸遍歷script模塊中的所有代碼,發(fā)現(xiàn)ctx.propsDestructuredBindings對象中什么都沒有。自然也不會將localName替換為__props.name,這樣他當然就會丟失響應式了。
總結
在編譯階段首先會處理宏函數(shù)defineProps,在處理的過程中如果發(fā)現(xiàn)解構了defineProps的返回值,那么就會將解構的name屬性,以及name解構到本地的localName變量,都全部一起存到ctx.propsDestructuredBindings對象中。
接下來就會去遞歸遍歷script模塊中的所有代碼,如果發(fā)現(xiàn)使用的localName變量能夠在ctx.propsDestructuredBindings對象中找的到。那么就說明這個localName變量是由props解構得到的,就會將其替換為__props.name,所以使用解構后的props依然不會丟失響應式。
另外歐陽寫了一本開源電子書vue3編譯原理揭秘,看完這本書可以讓你對vue編譯的認知有質的提升。這本書初、中級前端能看懂,完全免費,只求一個star。
相關文章
vue?element-ui的table列表中展示多張圖片(可放大)效果實例
這篇文章主要給大家介紹了關于vue?element-ui的table列表中展示多張圖片(可放大)效果的相關資料,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-08-08
在vue+element-plus中無法同時使用v-for和v-if的問題及解決方法
由于路由中存在不需要遍歷的數(shù)據(jù)所以像用v-if來過濾,但是報錯,百度說vue不能同時使用v-if和v-for,今天小編給大家分享解決方式,感興趣的朋友跟隨小編一起看看吧2023-07-07
Vite結合whistle實現(xiàn)一勞永逸開發(fā)環(huán)境代理方案
這篇文章主要為大家介紹了Vite結合whistle實現(xiàn)一勞永逸開發(fā)環(huán)境代理方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
Vue處理循環(huán)數(shù)據(jù)流程示例精講
這篇文章主要介紹了Vue處理循環(huán)數(shù)據(jù)流程,這個又是一個編程語言,?模版語法里面必不可少的一個,?也是使用業(yè)務場景使用最多的一個環(huán)節(jié)。所以學會使用循環(huán)也是重中之重了2023-04-04
詳解.vue文件中監(jiān)聽input輸入事件(oninput)
本篇文章主要介紹了詳解.vue文件中監(jiān)聽input輸入事件(oninput),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

