How to set default props in Vue
Setting default props is essential for creating robust Vue components that handle missing prop values gracefully while providing sensible fallbacks. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented default props in thousands of Vue components to ensure backward compatibility and improve developer experience in enterprise applications. From my expertise, the most effective approach is to use the default option in props definitions with proper type checking. This method provides type safety, clear documentation, and automatic fallback behavior while maintaining component flexibility.
Use the default option in props definition to set fallback values for missing component properties.
<template> <div class="user-card"> <h3>{{ name }}</h3> <p>{{ role }}</p> <p>Posts: {{ postsCount }}</p> <div :class="{ active: isActive }"> {{ isActive ? 'Online' : 'Offline' }} </div> </div> </template> <script> export default { props: { name: { type: String, default: 'Anonymous User' }, role: { type: String, default: 'Member' }, postsCount: { type: Number, default: 0 }, isActive: { type: Boolean, default: false }, settings: { type: Object, default: () => ({ theme: 'light', notifications: true }) } } } </script>
Default props are defined using the default option within prop definitions. For primitive values like strings, numbers, and booleans, use direct values. For objects and arrays, always use functions that return new instances to avoid shared references between component instances. Default values are applied when props are undefined, providing predictable fallback behavior.
Best Practice Note:
This is the same approach we use in CoreUI Vue components for reliable prop handling and component flexibility.