针对类型的
defineProps
声明的不足之处在于,它没有可以给 props 提供默认值的方式。为了解决这个问题,我们还提供了withDefaults
编译器宏:
- 引入
withDefaults
import { withDefaults } from 'vue'
- 声明定义
Props
// 在children.vue中
interface Props {
type: string;
items: any[];
subText?: string;
subTextFontSize?: string;
imageSize?: number;
columnNumber?: number;
gap?: string;
playButtonSize?: number;
}
- 通过
withDefaults
给props
设置默认值
// 在children.vue中
const props = withDefaults(defineProps<Props>(), {
subText: '',
subTextFontSize: '16px',
imageSize: 0,
columnNumber: 5,
gap: '44px 24px',
playButtonSize: 22
})
- 父组件给子组件传递值
<children
:type="'playlist'"
:items="byAppleMusic"
sub-text="appleMusic"
:image-size="1024"
/>