Vue3+ts获取props的default值: withDefaults

6,901 阅读1分钟

withDefaults的作用是给defineProps绑定默认值
引入 withDefaults

import {  withDefaults } from 'vue'

声明定义Props

// 在CoverRow.vue中
interface Props {
    // 类型
    type: string;
    items: any[];
    // 二级标题
    subText?: string;
    subTextFontSize?: string;
    // 图片尺寸
    imageSize?: number;
    // 一行多少个
    columnNumber?: number;
    // 间距
    gap?: string;
    // 播放按钮大小
    playButtonSize?: number;
}

通过withDefaults给props设置默认值

// 在CoverRow.vue中
const props = withDefaults(defineProps<Props>(), {
    subText: '',
    subTextFontSize: '16px',
    imageSize: 0,
    columnNumber: 5,
    gap: '44px 24px',
    playButtonSize: 22
})

父组件给子组件传递值

    <CoverRow 
      :type="'playlist'" 
      :items="byAppleMusic" 
      sub-text="appleMusic" 
      :image-size="1024" 
    />

打印输出props

image.png