Vue3 props的withDefaults使用方法

文章讲述了在Vue3的ScriptSetup语法中,如何在子组件中使用withDefaults定义props的问题,以及两种可能的写法。作者对withDefaults在编译时的行为和实际运行时的差异进行了探讨。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

withDefaults使用

父组件

<script setup lang="ts">
import RefPractice from '@/components/ref_practice.vue'
import { type PersonIner } from '@/components/type'
import {ref, reactive} from 'vue'
let personList = reactive<PersonIner[]>([
  {id: 1, name: 'xxx', age: 18},
  {id: 2, name: 'xxx2', age: 19}
])
</script>

<template>
  <RefPractice :list="personList" @click="chackRef"></RefPractice>
</template>

子组件

<script setup lang="ts">
// withDefaults会飘红波浪线,This is only usable inside <script setup>, is compiled away in the output and should not be actually called at runtime.
// 可以正常运行的
// 有哪位好心人知道为啥吗
import { withDefaults,ref } from 'vue' 
import { type Persons } from '@/components/type'

// 第一种写法(箭头函数写 {花括号} 记得加 return)
withDefaults(defineProps<{list?:Persons}>(),{
  list: () => {
    return [{id: 3333, name: '毛利小五郎', age: 90}]
  }
})

// 第二种写法
// withDefaults(defineProps<{list?:Persons}>(),{
//   list: () => [{id: 3333, name: '毛利小五郎', age: 90}]
// })

</script>

<template>
  <div class="refPractice">
    <p v-for="item in list" :key="item.id">{{item.name}} - {{item.age}}</p>
  </div>
</template>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值