分享
Vue3中defineProps()功能和作用
输入“/”快速插入内容
Vue3中defineProps()功能和作用
飞书用户4443
2024年8月13日修改
defineProps
是 Vue 3 组合式 API(Composition API)中的一个辅助函数,用于在
<script setup>
语法糖中声明和使用组件的
props
。它简化了组件属性的定义和类型推断,使得代码更加简洁和易读。
1.
defineProps
作用
(1)
声明组件的
props
:
defineProps
用于在
<script setup>
块中声明和使用父组件传递给子组件的属性(props)。
(2)
类型推断
:在使用 TypeScript 时,
defineProps
能够自动推断
props
的类型,从而增强开发体验和代码的类型安全性。
2.使用场景
defineProps
仅在 Vue 3 的
<script setup>
语法糖中使用。
<script setup>
是一种更简洁的组件写法,能够将组件的逻辑和渲染放在同一个块中,避免了传统组件写法中的一些冗余代码。
3.基本用法
以下是
defineProps
的基本用法:
代码块
Plain Text
<template>
<div>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</template>
<script setup>
// 使用 defineProps 来声明和获取 props
const props = defineProps({
title: String,
content: String
});
// 现在可以直接使用 props.title 和 props.content
</script>
在上面的示例中:
•
在
<script setup>
中使用
defineProps
声明了两个
props
:
title
和
content
。
•
这些
props
可直接在模板中使用,如
{{ title }}
和
{{ content }}
。
4.TypeScript 支持
当使用 TypeScript 时,
defineProps
还可通过类型声明来增强类型推断。
代码块
Plain Text
<template>
<div>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</template>
<script setup lang="ts">
// 使用 TypeScript 定义 props 类型
interface Props {
title: string;
content: string;
}
// 使用 defineProps 来获取 props,并自动推断类型
const props = defineProps<Props>();
</script>