如何在 Vue 3 中使用使用 `defineProps` 函数在 `setup` 中获取 props

在 Vue 3 中,defineProps 是 Composition API 的一部分,用于在 <script setup> 语法中定义组件的 props。这个函数用于声明组件期望接收的属性(props),并且可以进行类型检查和验证。

以下是如何在 Vue 3 的 setup 函数中使用 defineProps 来获取 props 的步骤:

1. 导入 defineProps 函数

首先,你需要从 vue 包中导入 defineProps 函数。

import { defineProps } from 'vue';

2. 使用 defineProps 定义 Props

<script setup> 中,使用 defineProps 来定义你的组件 props。你可以传递一个对象,对象的属性就是你想要定义的 props,以及它们的类型和验证器。

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  title: String,
  message: {
    type: String,
    default: ''
  },
  count: {
    type: Number,
    required: true
  }
});
</script>

在上面的例子中,title 是一个字符串类型的 prop,message 是一个带有默认值的字符串类型的 prop,而 count 是一个必需的数字类型的 prop。

3. 在模板中使用 Props

定义了 props 之后,你可以在组件的模板中像使用数据一样使用它们。

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
    <button @click="count++">Count is: {{ count }}</button>
  </div>
</template>

4. 完整的组件示例

下面是一个完整的 Vue 3 组件示例,展示了如何使用 defineProps

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
    <button @click="count++">Count is: {{ count }}</button>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  title: String,
  message: {
    type: String,
    default: ''
  },
  count: {
    type: Number,
    required: true
  }
});
</script>

在这个组件中,titlemessagecount 是从父组件传递下来的 props。你可以在模板中直接使用这些 props,并且它们将自动更新如果父组件改变了传递给它们的值。

5. 类型推断和 TypeScript

如果你在使用 TypeScript,defineProps 还支持类型推断,这样你就不需要显式地声明每个 prop 的类型。

<script setup lang="ts">
const props = defineProps({
  title: 'My Component',
  message: 'Hello, World!',
  count: 0
});
</script>

在这种情况下,TypeScript 将根据对象的字面量类型推断 props 的类型。

总结

defineProps 是 Vue 3 <script setup> 语法中定义组件 props 的一种简洁而强大的方式来。它不仅提供了类型检查和默认值的功能,还使得组件的 API 声明更加清晰和集中。通过使用 defineProps,你可以轻松地为你的组件声明和管理 props。


最后问候亲爱的朋友们,并邀请你们阅读我的全新著作

书籍详情
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JJCTO袁龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值