- Biết cách tạo component trong Vue
- Truyền dữ liệu từ cha → con bằng
props
- Biết cách sử dụng component nhiều lần
Component là một khối giao diện độc lập, có thể tái sử dụng nhiều nơi.
Ví dụ: <button-custom>
, <user-card>
, <product-box>
…
- Bạn chia nhỏ giao diện thành component
- Mỗi component có:
- Template (HTML)
- Data riêng
- Logic riêng (methods, computed…)
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Vue Components</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<style>
body {
font-family: Arial;
display: flex;
gap: 30px;
padding: 20px;
}
.code {
width: 50%;
}
.output {
width: 50%;
border-left: 2px solid #ccc;
padding-left: 20px;
}
.user-card {
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.user-card h4 {
margin: 0;
}
</style>
</head>
<body>
<div class="code">
<h2>Mã nguồn Vue:</h2>
<pre><code><div id="app">
<user-card
v-for="(user, index) in users"
:key="index"
:name="user.name"
:email="user.email"
></user-card>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
users: [
{ name: 'Nguyễn Văn A', email: 'a@example.com' },
{ name: 'Trần Thị B', email: 'b@example.com' },
{ name: 'Lê Văn C', email: 'c@example.com' }
]
}
},
components: {
'user-card': {
props: ['name', 'email'],
template: `
<div class="user-card">
<h4>👤 {{ name }}</h4>
<p>📧 {{ email }}</p>
</div>
`
}
}
}).mount('#app')
</script>
</code></pre>
</div>
<div class="output">
<h2>Kết quả hiển thị:</h2>
<div id="app"></div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
users: [
{ name: 'Nguyễn Văn A', email: 'a@example.com' },
{ name: 'Trần Thị B', email: 'b@example.com' },
{ name: 'Lê Văn C', email: 'c@example.com' }
]
}
},
components: {
'user-card': {
props: ['name', 'email'],
template: `
<div class="user-card">
<h4>👤 {{ name }}</h4>
<p>📧 {{ email }}</p>
</div>
`
}
}
}).mount('#app')
</script>
</body>
</html>
Thành phần | Ý nghĩa |
---|---|
components: { 'user-card': { ... } } | Đăng ký component user-card |
props: ['name', 'email'] | Nhận dữ liệu từ component cha |
template: ... | HTML của component |
<user-card name="Minh" email="minh@gmail.com"></user-card>
<user-card name="Linh" email="linh@gmail.com"></user-card>
→ Bạn không cần viết lại HTML nhiều lần.
- Thêm prop
avatar
và hiển thị hình đại diện<img :src="avatar">
- Thêm nút “Xem thêm” và bắt sự kiện
@click
để hiển thị alert - Dùng component để hiển thị danh sách sản phẩm (
name
,price
)
Thảo luận