• 为什么defineProps宏函数不需要从vue中import导入?


    前言

    我们每天写vue代码时都在用defineProps,但是你有没有思考过下面这些问题。为什么defineProps不需要import导入?为什么不能在非setup顶层使用definePropsdefineProps是如何将声明的 props 自动暴露给模板?

    举几个例子

    我们来看几个例子,分别对应上面的几个问题。

    先来看一个正常的例子,common-child.vue文件代码如下:

    <template>
      <div>content is {{ content }}div>
    template>
    
    <script setup lang="ts">
    defineProps({
      content: String,
    });
    script>
    

    我们看到在这个正常的例子中没有从任何地方import导入defineProps,直接就可以使用了,并且在template中渲染了props中的content

    我们再来看一个在非setup顶层使用defineProps的例子,if-child.vue文件代码如下:

    <template>
      <div>content is {{ content }}div>
    template>
    
    <script setup lang="ts">
    import { ref } from "vue";
    const count = ref(10);
    
    if (count.value) {
      defineProps({
        content: String,
      });
    }
    script>
    

    代码跑起来直接就报错了,提示defineProps is not defined

    通过debug搞清楚上面几个问题

    在我的上一篇文章 vue文件是如何编译为js文件 中已经带你搞清楚了vue文件中的包含结束标签后面的内容全部删掉,也就是删除结束标签和