defineProps 的使用方法

1. 基本用法

在 <script setup> 中,使用 defineProps 来定义 props

<template>
  <div>
    <p>{{ message }}</p>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
// 使用 defineProps 定义 props
const props = defineProps({
  message: {
    type: String,
    required: true
  },
  count: {
    type: Number,
    default: 0
  }
});
</script>

2. 使用 TypeScript 类型

如果你使用 TypeScript,可以通过泛型的方式定义 props 的类型

<script setup lang="ts">
interface Props {
  message: string;
  count?: number;
}

// 使用 TypeScript 泛型定义 props
const props = defineProps<Props>();
</script>

3. 默认值

在 TypeScript 中,如果需要为 props 提供默认值,可以使用 withDefaults 。

<script setup lang="ts">
interface Props {
  message: string;
  count?: number;
}

// 使用 withDefaults 提供默认值
const props = withDefaults(defineProps<Props>(), {
  count: 0
});
</script>

4. 在模板中使用

defineProps 返回的对象可以直接在模板中使用。

<template>
  <div>
    <p>{{ message }}</p>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
const props = defineProps({
  message: String,
  count: Number
});
</script>

5. 父组件传递数据

父组件通过 v-bind 或简写 : 向子组件传递数据。

<template>
  <div>
    <ChildComponent message="Hello from Parent" :count="42" />
  </div>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>

6. 注意事项

  • defineProps 只能在 <script setup> 中使用。

  • defineProps 是编译器宏,不需要显式导入。

  • props 是只读的,不能在子组件中直接修改。

7. 完整示例

子组件 (ChildComponent.vue)
<template>
  <div>
    <p>{{ message }}</p>
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
const props = defineProps({
  message: {
    type: String,
    required: true
  },
  count: {
    type: Number,
    default: 0
  }
});
</script>
父组件 (ParentComponent.vue)
<template>
  <div>
    <ChildComponent message="Hello from Parent" :count="42" />
  </div>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值