Vue3.5中響應式Props解構(gòu)的編譯原理
前言
在Vue3.5版本中響應式 Props 解構(gòu)終于正式轉(zhuǎn)正了,這個功能之前一直是試驗性的。這篇文章來帶你搞清楚,一個String類型的props經(jīng)過解構(gòu)后明明應該是一個常量了,為什么還沒丟失響應式呢?本文中使用的Vue版本為歐陽寫文章時的最新版Vue3.5.5
看個demo
我們先來看個解構(gòu)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給解構(gòu)出來了并且賦值給了localName,講道理解構(gòu)出來的localName應該是個常量會丟失響應式的,其實不會丟失。
我們在瀏覽器中來看一下編譯后的子組件代碼,很簡單,直接在network中過濾子組件的名稱即可,如下圖:
從上面可以看到原本的console.log(localName)
經(jīng)過編譯后就變成了console.log(__props.name)
,這樣當然就不會丟失響應式了。
我們再來看一個另外一種方式解構(gòu)的例子,這種例子解構(gòu)后就會丟失響應式,子組件代碼如下:
<template> {{ localName }} </template> <script setup lang="ts"> const props = defineProps(["name"]); const { name: localName } = props; console.log(localName); </script>
在上面的例子中我們不是直接解構(gòu)defineProps
的返回值,而是將返回值賦值給props
對象,然后再去解構(gòu)props
對象拿到localName
。
從上圖中可以看到這種寫法使用解構(gòu)的localName
時,就不會在編譯階段將其替換為__props.name
,這樣的話localName
就確實是一個普通的常量了,當然會丟失響應式。
這是為什么呢?為什么這種解構(gòu)寫法就會丟失響應式呢?別著急,我接下來的文章會講。
從哪里開下手?
既然這個是在編譯時將localName
處理成__props.name
,那我們當然是在編譯時debug了。
還是一樣的套路,我們在vscode中啟動一個debug
終端。
在之前的 通過debug搞清楚.vue文件怎么變成.js文件文章中我們已經(jīng)知道了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(), }; }
入?yún)?code>sfc對象:是一個descriptor
對象,descriptor
對象是由vue文件編譯來的。descriptor
對象擁有template屬性、scriptSetup屬性、style屬性,分別對應vue文件的<template>
模塊、<script setup>
模塊、<style>
模塊。
ctx
上下文對象:這個ctx
對象貫穿了整個script模塊的處理過程,他是根據(jù)vue文件的源代碼初始化出來的。在compileScript
函數(shù)中處理script模塊中的內(nèi)容,實際就是對ctx
對象進行操作。最終ctx.s.toString()
就是返回script模塊經(jīng)過編譯后返回的js代碼。
搞清楚了入?yún)?code>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里面還有一個內(nèi)層for循環(huán),這個for循環(huán)是在遍歷node節(jié)點的declarations
屬性,這個屬性是一個數(shù)組。
declarations
數(shù)組屬性表示當前變量聲明語句中定義的所有變量,可能會定義多個變量,所以他才是一個數(shù)組。在我們這里只定義了一個變量localName
,所以 declarations
數(shù)組中只有一項。
在內(nèi)層for循環(huán),會去遍歷聲明的變量,然后從變量的節(jié)點中取出init
屬性。我想聰明的你從名字應該就可以看出來init
屬性的作用是什么。
沒錯,init
屬性就是對應的變量的初始化值。在我們這里聲明的localName
變量的初始化值就是defineProps(["name"])
函數(shù)的返回值。
接著就是判斷init
是否存在,也就是判斷變量是否是有初始化值。如果為真,那么就執(zhí)行processDefineProps(ctx, init, decl.id)
判斷初始化值是否是在調(diào)用defineProps
。換句話說就是判斷當前的變量聲明是否是在調(diào)用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導入?文章中我們已經(jīng)講過了這里的第一個if語句就是用于判斷當前是否在執(zhí)行defineProps
函數(shù),如果不是那么就直接return false
我們接著來看第二個if語句,這個if語句就是判斷當前變量聲明是不是“對象解構(gòu)賦值”。很明顯我們這里就是解構(gòu)出的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); } }
前面講過了這里的兩個入?yún)ⅲ?code>ctx表示當前上下文對象。declId
表示變量聲明語句中的變量名稱。
首先定義了一個名為registerBinding
的箭頭函數(shù)。
接著就是使用for循環(huán)遍歷declId.properties
變量名稱,為什么會有多個變量名稱呢?
答案是解構(gòu)的時候我們可以解構(gòu)一個對象的多個屬性,用于定義多個變量。
prop
屬性如下圖:
從上圖可以看到prop
中有兩個屬性很顯眼,分別是key
和value
。
其中key
屬性對應的是解構(gòu)對象時從對象中要提取出的屬性名,因為我們這里是解構(gòu)的name
屬性,所以上面的值是name
。
其中value
屬性對應的是解構(gòu)對象時要賦給的目標變量名稱。我們這里是賦值給變量localName
,所以上面他的值是localName
。
接著來看for循環(huán)中的代碼。
執(zhí)行const propKey = resolveObjectKey(prop.key)
拿到要從props
對象中解構(gòu)出的屬性名稱。
將斷點走進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ù)為傳入解構(gòu)對象時要提取出的屬性名稱,也就是name
。第二個參數(shù)為解構(gòu)對象時要賦給的目標變量名稱,也就是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上下文中的一個屬性對象,這個對象里面存的是需要解構(gòu)的多個props。
對象的key就是需要解構(gòu)的props。
key對應的value也是一個對象,這個對象中有兩個字段。其中的local
屬性是解構(gòu)props后要賦給的變量名稱。default
屬性是props的默認值。
在debug終端來看看此時的ctx.propsDestructuredBindings
對象是什么樣的,如下圖:
從上圖中就有看到此時里面已經(jīng)存了一個name
屬性,表示props
中的name
需要解構(gòu),解構(gòu)出來的變量名為localName
,并且默認值為undefined
。
經(jīng)過這里的處理后在ctx上下文對象中的ctx.propsDestructuredBindings
中就已經(jīng)存了有哪些props需要解構(gòu),以及解構(gòu)后要賦值給哪個變量。
有了這個后,后續(xù)只需要將script模塊中的所有代碼遍歷一次,然后找出哪些在使用的變量是props解構(gòu)的變量,比如這里的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(), }; }
經(jīng)過processDefineProps
函數(shù)的處理后,ctx.propsDestructureDecl
對象中已經(jīng)存了有哪些變量是由props解構(gòu)出來的。
這里的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是解構(gòu)了哪些props,比如這里就是解構(gòu)了name
這個props。
接著就是使用const { local } = ctx.propsDestructuredBindings[key]
拿到解構(gòu)的props在子組件中賦值給了哪個變量,我們這里是解構(gòu)出來后賦給了localName
變量,所以這里的local
的值為字符串"localName"。
由于在我們這個demo中只有兩行代碼,分別是解構(gòu)props和console.log
。沒有其他的函數(shù),所以這里的作用域只有一個。也就是說rootScope
始終等于currentScope
。
所以這里執(zhí)行rootScope[local] = true
后,currentScope
對象中的localName
屬性也會被賦值true。如下圖:
接著就是執(zhí)行propsLocalToPublicMap[local] = key
,這里的local
存的是解構(gòu)props后賦值給子組件中的變量名稱,key
為解構(gòu)了哪個props。經(jīng)過這行代碼的處理后我們就形成了一個映射,后續(xù)根據(jù)這個映射就能輕松的將script模塊中使用解構(gòu)后的localName
的地方替換為__props.name
。
propsLocalToPublicMap
對象如下圖:
經(jīng)過這個for循環(huán)的處理后,我們已經(jīng)知道了有哪些變量其實是經(jīng)過props解構(gòu)來的,以及這些解構(gòu)得到的變量和props的映射關(guān)系。
接下來就是使用walk
函數(shù)去遞歸遍歷script模塊中的所有代碼,這個遞歸遍歷就是遍歷script模塊對應的AST抽象語法樹。
在這里是使用的walk
函數(shù)來自于第三方庫estree-walker
。
在遍歷語法樹中的某個節(jié)點時,進入的時候會觸發(fā)一次enter
回調(diào),出去的時候會觸發(fā)一次leave
回調(diào)。
walk
函數(shù)的執(zhí)行代碼如下:
walk(ast, { enter(node: Node) { if (node.type === "Identifier") { if (currentScope[node.name]) { rewriteId(node); } } }, });
我們這個場景中只需要enter
進入的回調(diào)就行了。
在enter
回調(diào)中使用外層if判斷當前節(jié)點的類型是不是Identifier
,Identifier
類型可能是變量名、函數(shù)名等。
我們源代碼中的console.log(localName)
中的localName
就是一個變量名,當遞歸遍歷AST抽象語法樹遍歷到這里的localName
對應的節(jié)點時就會滿足外層的if條件。
在debug終端來看看此時滿足外層if條件的node節(jié)點,如下圖:
從上面的代碼可以看到此時的node節(jié)點中對應的變量名為localName
。其中start
和end
分別表示localName
變量的開始位置和結(jié)束位置。
我們回憶一下前面講過了currentScope
對象中就是存的是有哪些本地的變量是通過props解構(gòu)得到的,這里的localName
變量當然是通過props解構(gòu)得到的,滿足里層的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ù)是:結(jié)束位置,對應的是變量localName
在源碼中的結(jié)束位置。
第三個參數(shù)是想要替換成的新內(nèi)容。
第三個參數(shù)是由genPropsAccessExp
函數(shù)返回的,執(zhí)行這個函數(shù)時傳入的是propsLocalToPublicMap[id.name]
。
前面講過了propsLocalToPublicMap
存的是props名稱和解構(gòu)到本地的變量名稱的映射關(guān)系,id.name
是解構(gòu)到本地的變量名稱。如下圖:
所以propsLocalToPublicMap[id.name]
的執(zhí)行結(jié)果就是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
方法的地方,此時我們已經(jīng)知道了第三個參數(shù)的值為__props.name
。這個方法的執(zhí)行會將localName
重寫為__props.name
在ctx.s.overwrite
方法執(zhí)行之前我們來看看此時的script模塊中的js代碼是什么樣的,如下圖:
從上圖中可以看到此時的代碼中console.log
里面還是localName
。
執(zhí)行完ctx.s.overwrite
方法后,我們來看看此時是什么樣的,如下圖:
從上圖中可以看到此時的代碼中console.log
里面已經(jīng)變成了__props.name
。
這就是在編譯階段將使用到的解構(gòu)localName
變量變成__props.name
的完整過程。
這會兒我們來看前面那個例子解構(gòu)后丟失響應式的例子,我想你就很容易想通了。
<script setup lang="ts"> const props = defineProps(["name"]); const { name: localName } = props; console.log(localName); </script>
在處理defineProps
宏函數(shù)時,發(fā)現(xiàn)是直接解構(gòu)了返回值才會進行處理。上面這個例子中沒有直接進行解構(gòu),而是將其賦值給props
,然后再去解構(gòu)props
。這種情況下ctx.propsDestructuredBindings
對象中什么都沒有。
后續(xù)在遞歸遍歷script模塊中的所有代碼,發(fā)現(xiàn)ctx.propsDestructuredBindings
對象中什么都沒有。自然也不會將localName
替換為__props.name
,這樣他當然就會丟失響應式了。
總結(jié)
在編譯階段首先會處理宏函數(shù)defineProps
,在處理的過程中如果發(fā)現(xiàn)解構(gòu)了defineProps
的返回值,那么就會將解構(gòu)的name
屬性,以及name
解構(gòu)到本地的localName
變量,都全部一起存到ctx.propsDestructuredBindings
對象中。
接下來就會去遞歸遍歷script模塊中的所有代碼,如果發(fā)現(xiàn)使用的localName
變量能夠在ctx.propsDestructuredBindings
對象中找的到。那么就說明這個localName
變量是由props解構(gòu)得到的,就會將其替換為__props.name
,所以使用解構(gòu)后的props依然不會丟失響應式。
另外歐陽寫了一本開源電子書vue3編譯原理揭秘,看完這本書可以讓你對vue編譯的認知有質(zhì)的提升。這本書初、中級前端能看懂,完全免費,只求一個star。
相關(guān)文章
vue?element-ui的table列表中展示多張圖片(可放大)效果實例
這篇文章主要給大家介紹了關(guān)于vue?element-ui的table列表中展示多張圖片(可放大)效果的相關(guān)資料,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-08-08在vue+element-plus中無法同時使用v-for和v-if的問題及解決方法
由于路由中存在不需要遍歷的數(shù)據(jù)所以像用v-if來過濾,但是報錯,百度說vue不能同時使用v-if和v-for,今天小編給大家分享解決方式,感興趣的朋友跟隨小編一起看看吧2023-07-07Vite結(jié)合whistle實現(xiàn)一勞永逸開發(fā)環(huán)境代理方案
這篇文章主要為大家介紹了Vite結(jié)合whistle實現(xiàn)一勞永逸開發(fā)環(huán)境代理方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07Vue處理循環(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