Vue3 子组件定义默认值withDefaults

  • 如果父组件为传递子组件数据, 子组件可以使用withDefaults定义默认值

父组件

<template>
  <div>
    <PageData :num="num" name="传给子组件的值"></PageData>
  </div>
</template>

<script setup lang="ts">
import PageData from './pages/page.vue'
import {
    
     reactive } from 'vue'

const num  = reactive<number[]>([1,2,3]) // 传递给子组件

</script>

<style scoped>

</style>

子组件

<template>
    <div>
       子组件: {
    
    {
    
    name}}
       <div v-for="(item, index) in num" :key="index">{
    
    {
    
    item}}</div>
    </div>
</template>

<script setup lang="ts">
import {
    
     reactive } from 'vue'

// ts
type Props = {
    
    
    name?:string,
    num?:number[]
}


// withDefaults 定义默认值
withDefaults(defineProps<Props>(), {
    
    
    name: 'zs',
    num: () => [12,13,14] // 复杂数据类型使用函数方式
})

</script>

<style scoped>

</style>

猜你喜欢

转载自blog.csdn.net/qq_52099965/article/details/127451595
今日推荐