Handling Props in Vue Components

Jul 14, 2024

Handling Props in Vue Components

Overview

  • Props: Allow passing data from a parent component to a child component.
  • Goal: Show a clean and organized way to handle passing objects as props in Vue components.
  • Demo: Built using Nuxt 3 (also applicable to Vue 3).

Demo Details

  • User Object: Created using ref and typed with a UserType imported at the top of the script tag.
  • Components: App.vue has a UserCard component with basic Vue file structure.
  • Define Props: Macro used to define props within the UserCard component.

Typical Approach

  • Passing Object as Prop:
    • Define user prop on UserCard:
      <UserCard :user="user" />
      
    • Define prop within UserCard component:
      const props = defineProps({
        user: UserType
      });
      
    • Access prop inside the template:
      <div>{{ user.firstName }}</div>
      
  • Issues:
    • Granular and non-specific, which can be unclear when dealing with larger objects.

Preferred Approach

  • Specific Prop Declaration:
    • Create props for each property within the object.
    • Example with four properties (ID, First Name, Last Name, Email):
      const props = defineProps({
        id: UserType['id'],
        firstName: UserType['firstName'],
        lastName: UserType['lastName'],
        email: UserType['email']
      });
      
    • Remove the singular user prop.

Practical Changes

  • Parent Component Updates:
    • Remove the single user prop.
    • Bind user object properties individually or use v-bind to bind entire object:
      <UserCard v-bind="user" />
      
  • Efficiency:
    • v-bind destructures object properties and binds them to designated props within the component.
    • Cleaner, more efficient, and clearer prop management.

Conclusion

  • Benefits: Clearer code, easier to understand which props are used within the component, and more efficient binding.
  • Future Content: Upcoming course release on Nuxt, additional frontend challenges via a new application called Web Dev Daily.

Resources

  • Learn Nuxt Course: Join the waiting list on learn N.D.
  • Web Dev Daily: Free frontend challenges with a browser IDE.