vue3 defineProps function

In vue2, we use the props in the options to accept the data passed by the parent component; in the setup of vue3, we use defineProps to define the data passed by the parent component.

1. The types supported by defineProps are: String, Number, Boolean, Object, Array, and Function. In addition, it also supports many advanced types, such as: enumeration types, object types, and union types.

2. Verification of props

type: 定义数据的类型
reqiured: 是否必须
default: 默认值
validator: 自定义验证

3. Use

3.1 <script setup>Use in

<template>
  <div>
  {
   
   { msg }} - {
   
   { name }} - {
   
   { age }}
  <button @click="() => onClick()">点击事件</click>
 </div>
<template>

<script setup>
// defineProps 返回一个对象,可以定义任意的变量去接收这个对象

// 方式1: 以对象的形式去接收
const props = defineProps({
 name: String,
 age: {
  type: Number,
  default: 10,
  reqiured: true,
  validator: (val) => val > 10
 },
 msg: {
  type: String,
  default: () => 'this is a default msg'
 },
 onClik: Function
})
// props.age = 18 // 报错,注意 defineProps 中的属性只读不能修改


// 方式2: 以数组的方式去接收
const childProps = defineProps(['name', 'age', 'msg', 'onClick'])
</script>

3.2 <script lang="ts" setup>Used in , no default value

<template>
  <div>
  {
   
   { msg }} - {
   
   { name }} - {
   
   { age }}
  <button @click="() => onClick()">点击事件</click>
 </div>
<template>

<script lang="ts" setup>

// 采用 ts 声明无默认值

interface ChildPropsType {
  name: string
  age: number
  msg: string
  onClick: () => void
}

const props = defineProps<ChildPropsType>()
</script>

3.3 <script lang="ts" setup>Used in , with default value

<template>
  <div>
  {
   
   { msg }} - {
   
   { name }} - {
   
   { age }}
  <button @click="() => onClick()">点击事件</click>
 </div>
<template>

<script lang="ts" setup>

// 采用 ts 声明有默认值;由于接口不能设置默认值,所以要使用 withDefaults 编译宏来实现

interface ChildPropsType {
  name: string
  age: number
  msg: string
  onClick: () => void
}

const props = withDefaults(defineProps<ChildPropsType>(), {
  name: 'bob',
  age: 17,
  msg: 'this is a default msg'
})
</script>

4. Things to note

① defineProps can only be used in setup, and can only be used at the top level of setup, and cannot be used in local scopes.

② Like vue2, the properties in defineProps are read-only and cannot be modified.

③ defineProps is a macro function of vue3, which can be used directly without importing it.

④ The defineProps function returns an object, which is a proxy. All features are basically the same as reactive and can be used directly on the template.

Guess you like

Origin blog.csdn.net/qq_37600506/article/details/132733654