Mục tiêu:
- Biết cách khai báo methods (hàm xử lý) trong Vue
- Biết cách bắt sự kiện click, input, submit bằng
v-on
/ @
- Làm ứng dụng đếm số và xử lý form đơn giản
Các kiến thức chính:
Tính năng | Vue Cú pháp | Ghi chú |
---|
Gọi hàm khi click | @click="tenHam" | Viết trong methods |
Truyền tham số | @click="tenHam(giaTri)" | Có thể truyền biến |
Sự kiện khác | @input , @submit , @mouseover | Vue hỗ trợ mọi sự kiện HTML |
Giao diện học (Code + Output)
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Vue Methods & Events</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;
}
button {
margin: 5px;
}
input {
padding: 5px;
}
</style>
</head>
<body>
<div class="code">
<h2>Mã nguồn Vue:</h2>
<pre><code><div id="app">
<!-- 1. Bộ đếm -->
<h3>Bộ đếm: {{ count }}</h3>
<button @click="count++">+ Tăng</button>
<button @click="count--">- Giảm</button>
<button @click="resetCount">🧹 Reset</button>
<!-- 2. Xử lý Form -->
<h3>Nhập tên của bạn:</h3>
<form @submit.prevent="handleSubmit">
<input v-model="username" placeholder="Nhập tên...">
<button type="submit">Gửi</button>
</form>
<p>Xin chào, {{ submittedName }}!</p>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
count: 0,
username: '',
submittedName: ''
}
},
methods: {
resetCount() {
this.count = 0;
},
handleSubmit() {
this.submittedName = this.username;
this.username = '';
}
}
}).mount('#app')
</script>
</code></pre>
</div>
<div class="output">
<h2>Kết quả hiển thị:</h2>
<div id="app">
<!-- 1. Bộ đếm -->
<h3>Bộ đếm: {{ count }}</h3>
<button @click="count++">+ Tăng</button>
<button @click="count--">- Giảm</button>
<button @click="resetCount">🧹 Reset</button>
<!-- 2. Xử lý Form -->
<h3>Nhập tên của bạn:</h3>
<form @submit.prevent="handleSubmit">
<input v-model="username" placeholder="Nhập tên...">
<button type="submit">Gửi</button>
</form>
<p>Xin chào, {{ submittedName }}!</p>
</div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
count: 0,
username: '',
submittedName: ''
}
},
methods: {
resetCount() {
this.count = 0;
},
handleSubmit() {
this.submittedName = this.username;
this.username = '';
}
}
}).mount('#app')
</script>
</body>
</html>
Giải thích:
Câu lệnh | Tác dụng |
---|
@click="count++" | Tăng giá trị count khi click |
@click="resetCount" | Gọi hàm resetCount() trong methods |
@submit.prevent="handleSubmit" | Gửi form mà không reload trang |
v-model="username" | Gắn input với biến username |
Bài tập mở rộng:
- Thêm nút
"x2"
→ mỗi lần click nhân đôi count
.
- Nếu người dùng nhập tên
"admin"
→ hiển thị dòng "Chào sếp!"
.
- Hiển thị lịch sử tên đã gửi (mảng
historyNames
, dùng v-for
).
Thảo luận