
1. Tạo Component
Giả sử bạn muốn tạo 1 component hiển thị thông tin người dùng.
📂 Cấu trúc thư mục:
src/ ┣ components/ ┃ ┗ UserCard.vue ┣ App.vue ┣ main.js
UserCard.vue
<script setup> defineProps({ name: String, age: Number }) </script> <template> <div class="card"> <h3>{{ name }}</h3> <p>Tuổi: {{ age }}</p> </div> </template> <style scoped> .card { padding: 10px; border: 1px solid #ddd; margin-bottom: 10px; border-radius: 8px; } </style>
App.vue
<script setup> import UserCard from './components/UserCard.vue' </script> <template> <h1>Danh sách người dùng</h1> <UserCard name="Thanh" :age="25" /> <UserCard name="Lan" :age="22" /> </template>
2. Props – Truyền dữ liệu từ Cha → Con
-
Dùng
defineProps()
trong Composition API. -
Props có thể ràng buộc kiểu dữ liệu (
String
,Number
,Boolean
,Array
,Object
…).
Ví dụ: