-
为什么
defineProps
不需要import
导入?
因为在编译过程中如果当前AST抽象语法树
的节点类型是ExpressionStatement
表达式语句,并且调用的函数是defineProps
,那么就调用remove
方法将调用defineProps
函数的代码给移除掉。既然defineProps
语句已经被移除了,自然也就不需要import
导入了defineProps
了。
-
为什么不能在非
setup
顶层使用defineProps
?
因为在非setup
顶层使用defineProps
的代码生成AST抽象语法树
后节点类型就不是ExpressionStatement
表达式语句类型,只有ExpressionStatement
表达式语句类型才会走到processDefineProps
函数中,并且调用remove
方法将调用defineProps
函数的代码给移除掉。当代码运行在浏览器时由于我们没有从任何地方import
导入defineProps
,当然就会报错defineProps is not defined
。
-
defineProps
是如何将声明的props
自动暴露给模板?
编译时在移除掉defineProps
相关代码时会将调用defineProps
函数时传入的参数node
节点信息存到ctx
上下文中。遍历完AST抽象语法树后
,然后从上下文中存的参数node
节点信息中拿到调用defineProps
宏函数时传入props
的开始位置和结束位置。再使用slice
方法并且传入开始位置和结束位置,从<script setup>
模块的代码字符串中截取到props
定义的字符串。然后将截取到的props
定义的字符串拼接到vue
组件对象的字符串中,这样vue
组件对象中就有了一个props
属性,这个props
属性在template
模版中可以直接使用。
转载自微信公众号:前端欧阳