Handling Props in Vue/Nuxt Components

Jul 14, 2024

Handling Props in Vue/Nuxt Components

Introduction

  • Props are commonly used in Vue components to pass data from parent to child components.
  • Sending props as an object to child components can be done efficiently.
  • Demonstration created using Nuxt 3 (also applicable for Vue 3).

Demo Application Overview

  • Creating a user object using ref and typing it with a user type.
  • Example includes:
    • user type imported at the top of the script.
    • user card component with a typical view file structure.
    • Using DefineProps macro to define component props.

Passing User Object as a Prop

  • Take the user object and pass it to user card component using a prop.
  • Example Syntax:
    <UserCard :user="user" />
    
  • Inside UserCard component, use DefineProps macro to define user prop:
    const props = defineProps<{ user: User }>();
    
  • Display user prop values inside the template, e.g., user.firstName.

Problems with Object Prop Approach

  • Using an entire object as a prop lacks specificity.
  • Better practice: Create individual props for each property in the object.

Creating Individual Props for Object Properties

  • Example user object has four properties; create four separate props:
    const props = defineProps<{ id: number, firstName: string, lastName: string, email: string }>();
    
  • Eliminates the need for an entire object prop and makes specs more clear.

Updating Parent Component

  • Remove old object prop binding.
  • Instead of defining individual props in parent template, use v-bind to bind the entire object to child component in a single line.
    <UserCard v-bind="user" />
    
  • v-bind destructures the user object, making the parent component template cleaner.
  • Inside UserCard, only declare and use specific properties needed.

Conclusion

  • Using v-bind with object destructuring makes code more efficient and readable.
  • Enhanced clarity and specificity in component prop definitions.

Additional Information

  • Course on Nuxt releasing soon; details at learn N.D.
  • Front-end skills challenge application: Web Dev Daily. Free to join.