https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
为了在声明 props 选项时获得完整的类型推导支持,可以使用 defineProps API,它将自动地在 <script setup>
中可用:
<script setup>
<script setup>
const props = defineProps({
foo: String
})
</script>
defineProps 是只能在 <script setup>
中使用的编译器宏。不需要导入,且会随着 <script setup>
的处理过程一同被编译掉。
defineProps 接收与 props 选项相同的值。
传入到 defineProps 的选项会从 setup 中提升到模块的作用域。因此,传入的选项不能引用在 setup 作用域中声明的局部变量。这样做会引起编译错误。但是,它可以引用导入的绑定,因为它们也在模块作用域内。
例如,下面这段代码使用了编译器宏函数defineProps:
<script setup>
const props = defineProps({
message: String,
count: Number
})
console.log(props)
</script>
<template>
</template>
<style scoped></style>
将这段代码粘贴到Vue SFC Playground看看编译后的结果:
注意红框框出来的部分编译前后的对比: