- Hiểu cách cha truyền dữ liệu cho con bằng
props
- Hiểu cách component con gửi sự kiện ngược lại lên cha bằng
$emit
- Làm ví dụ nút
Vote
để gửi tín hiệu từ con → cha
Hướng giao tiếp | Cách làm |
---|
Cha → Con | Dùng props |
Con → Cha | Dùng $emit('eventName', data) và @eventName="handler" |
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Vue Props & Emit</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;
}
.item-box {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
button {
margin-top: 5px;
}
</style>
</head>
<body>
<div class="code">
<h2>Mã nguồn Vue:</h2>
<pre><code><div id="app">
<h3>Tổng số vote: {{ totalVotes }}</h3>
<vote-box
v-for="(item, index) in items"
:key="index"
:title="item"
@voted="handleVote"
></vote-box>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
totalVotes: 0,
items: ['Bài học Vue', 'React Tutorial', 'Angular Overview']
};
},
methods: {
handleVote() {
this.totalVotes++;
}
},
components: {
'vote-box': {
props: ['title'],
template: `
<div class="item-box">
<strong>{{ title }}</strong><br>
<button @click="vote">Vote +1</button>
</div>
`,
methods: {
vote() {
this.$emit('voted');
}
}
}
}
}).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 {
totalVotes: 0,
items: ['Bài học Vue', 'React Tutorial', 'Angular Overview']
};
},
methods: {
handleVote() {
this.totalVotes++;
}
},
components: {
'vote-box': {
props: ['title'],
template: `
<div class="item-box">
<strong>{{ title }}</strong><br>
<button @click="vote">Vote +1</button>
</div>
`,
methods: {
vote() {
this.$emit('voted');
}
}
}
}
}).mount('#app');
</script>
</body>
</html>
Thành phần | Tác dụng |
---|
:title="item" | Truyền prop title từ cha → con |
@voted="handleVote" | Lắng nghe sự kiện từ con emit lên |
this.$emit('voted') | Component con phát sự kiện voted lên cha |
- Cha truyền dữ liệu qua
props
- Con giao tiếp ngược qua
emit
- Rất hữu ích khi tái sử dụng component như: rating, vote, like, alert…
- Truyền thêm
score
từ con → cha khi vote ($emit('voted', score)
).
- Cho mỗi component
vote-box
có biến localVotes
, tăng lên mỗi khi bấm.
- Đổi
button
thành icon ❤️ (like), khi bấm hiện Đã thích
.
Thảo luận