defineProps() 和 defineEmits() 为什么不需要手动引入

711 阅读1分钟

一个小卡拉米的自我自学之路!

最近正在将一个UI组件的 Options APIVue2 JavaScript 项目升级为 Vue3 JavaScript,在升级的过程中一点点的了解了Composition API 的优势。

在使用过程中发现defineProps()defineEmits() 是可以直接使用的, 如下所示

<script setup> // setup 代码
const props = defineProps({ foo: String })

const emit = defineEmits(['change', 'delete'])

</script>

查询各种资料总觉得是答非所问,不是我想要的结果。最后还是在 vue文档 中找到了自己想要的答案,在此记录下:

image.png

文档所示: Vue3 为了在声明 props 和 emits 选项时获得完整的类型推导支持,我们可以使用 defineProps 和 defineEmits API,它们将自动地在 <script setup> 中可用:

  • defineProps 和 defineEmits 都是只能在 <script setup> 中使用的编译器宏。他们不需要导入,且会随着 <script setup> 的处理过程一同被编译掉。
  • defineProps 接收与 props 选项相同的值,defineEmits 接收与 emits 选项相同的值。
  • defineProps 和 defineEmits 在选项传入后,会提供恰当的类型推导。
  • 传入到 defineProps 和 defineEmits 的选项会从 setup 中提升到模块的作用域。因此,传入的选项不能引用在 setup 作用域中声明的局部变量。这样做会引起编译错误。但是,它可以引用导入的绑定,因为它们也在模块作用域内。

在此处可以看出defineProps()defineEmits() 只有在  <script setup> 中才能做到不需要手动引入,直接在js中使用!!!


小卡拉米就是小卡拉米啊,多多通读技术文档才是技术提升的王道

/*code is far away from bug with the animal protecting
*   ┏┓     ┏┓
*┏━━┛┻━━━━━┛┻┓
*┃      ┃  
*┃   ━   ┃
*┃ ┳┛ ┗┳   ┃
*┃      ┃
*┃   ┻   ┃
*┃       ┃
*┗━━┓    ┏━┛
*  ┃   ┃神兽保佑
*  ┃   ┃
*  ┃   ┗━━━┓
*  ┃      ┣┓
*  ┃     ┏┛
*  ┗━┓┓┏━━┳┓┏━┛
*   ┃┫┫ ┃┫┫
*   ┗┻┛ ┗┻┛ 
*   
*/