Vue.js Lesson 6: Components & Props

💚 Vue.js CourseLesson 6 of 10 · 60% complete

Components are reusable Vue files. Props pass data from parent to child, just like React but with a Vue-specific syntax.

Creating & Using Components

<!-- components/UserCard.vue -->
<template>
  <div class="user-card">
    <img :src="user.avatar || 'https://i.pravatar.cc/50?u='+user.id'" :alt="user.name" />
    <h3>{{ user.name }}</h3>
    <p>{{ user.email }}</p>
    <span :class="['badge', user.role]">{{ user.role }}</span>
  </div>
</template>

<script setup>
const props = defineProps({
  user: {
    type: Object,
    required: true
  }
});
</script>

<!-- App.vue -->
<template>
  <UserCard v-for="user in users" :key="user.id" :user="user" />
</template>

<script setup>
import UserCard from "./components/UserCard.vue";
import { ref } from "vue";
const users = ref([...]);
</script>

TypeScript Props

<!-- With TypeScript -->
<script setup lang="ts">
interface User { id: number; name: string; email: string; role: string; }

const props = defineProps<{
  user: User;
  isSelected?: boolean;
  onSelect?: (user: User) => void;
}>();
</script>

🏋️ Practice Task

Build a Card component system. BaseCard: slot for any content + optional title prop. ProductCard extends BaseCard: props (product: {id,name,price,image,rating}), shows image, name, stars, price, “Buy” button. Use in App.vue to show 4 products.

💡 Hint: OR just build ProductCard directly without slots.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *