1、Ts中接收父组件传递参数prop的定义写法:
<script setup lang="ts">defineProps<{title?: stringlikes?: number}>()
</script>
2、所有的 props 都遵循着单向绑定原则,props 因父组件的更新而变化,子组件中不能赋值更改。否则控制台上向你抛出警告!
想要没有告警,通常子组件中prop用法:
//prop作为初始值,重新定义一个响应式变量给这个prop作为初始值
1. const counter = ref(props.initialCounter)
//使用计算属性也可以,看使用场景
3. const normalizedSize = computed(() => props.size.trim().toLowerCase())
3、Prop 校验
官方例子(一目了然):
defineProps({// 基础类型检查// (给出 `null` 和 `undefined` 值则会跳过任何类型检查)propA: Number,// 多种可能的类型propB: [String, Number],// 必传,且为 String 类型propC: {type: String,required: true},// Number 类型的默认值propD: {type: Number,default: 100},// 对象类型的默认值propE: {type: Object,// 对象或数组的默认值// 必须从一个工厂函数返回。// 该函数接收组件所接收到的原始 prop 作为参数。default(rawProps) {return { message: 'hello' }}},// 自定义类型校验函数// 在 3.4+ 中完整的 props 作为第二个参数传入propF: {validator(value, props) {// The value must match one of these stringsreturn ['success', 'warning', 'danger'].includes(value)}},// 函数类型的默认值propG: {type: Function,// 不像对象或数组的默认,这不是一个// 工厂函数。这会是一个用来作为默认值的函数default() {return 'Default function'}}
})
校验选项中的 type 支持以下原生构造函数:
• String • Number • Boolean • Array • Object • Date • Function• Symbol • Error
也可自定义的类或构造函数:
class Person {constructor(firstName, lastName) {this.firstName = firstNamethis.lastName = lastName}
}
defineProps({author: Person
})