Vue3 defineProps使用指南
defineProps是Vue3组合式API( < script setup > )中专用来声明组件接受父组件传值的宏函数,无须导入,直接使用。他的核心:声明子组件要接收的props、定义类型校验、设置默认值、必填项。
一、基础用法(最简单)
直接声明props名称数组,适合简单场景:
<!-- 子组件 Child.vue -->
<script setup>
// 基础用法:只声明名称
defineProps(['title', 'count'])
</script>
<template>
<div>{{ title }}</div>
<div>{{ count }}</div>
</template>
父组件使用
<!-- 父组件 parent.vue -->
<Child title="我是标题" :cout="10" />
二、带校验的用法(推荐)
可以指定类型、必填、默认值,开发中很常见
<script setup>
defineProps({
// 基础类型校验 String/Number/Boolean/Array/Object/Function
title: {
type: String,
required: true, // 必填项
default: '默认标题' // 默认值
},
count: {
type: Number,
default: 0
},
// 多个可能的类型
id: [String, Number],
// 自定义校验函数
status: {
validator(value) {
// 必须是这几个值之一
return ['success', 'error', 'warning'].includes(value)
}
}
}) </script>
三、TS类型写法(Vue3+TypeScript)
如果用TS,推荐泛型写法,类型更安全
<script setup>
import {widthDefault} from "vue"
// 定义接口(推荐)
interface IProps {
title: string
count?: number //可选
list?: string[]
}
// 泛型+默认值
const props = withDefault(defineProps<IProps>(), {
count: 0,
list: ()=>[]
});
</script>
四、获取和使用props变量
widthDefault或者defineProps都会返回一个响应式对象,可以接收并使用
<script setup>
import { toRefs } from "vue"
// 接收 props 对象
const props = defineProps(['title', 'count']);
// 1.直接使用props.xxx方式使用
console.log(props.title)
console.log(props.count)
// 2.通过使用toRefs的方式解构props
// 注意不能直接结构props, 会丢失响应式
const {title, count} = toRefs(props);
console.log(title.value)
console.log(count.value)
</script>