Mục tiêu:
- Biết cách dùng Vue mà không cần cài đặt
- Hiển thị dòng chữ “Hello Vue!” từ data
- Thấy ngay sự thay đổi khi đổi dữ liệu
Kiến thức chính:
- Dùng CDN Vue 3 từ
https://unpkg.com
- Gắn Vue app vào 1 phần tử HTML (
#app
) - Dùng
{{ variable }}
để hiển thị data trong template
Mã nguồn:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Hello Vue!</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;
}
</style>
</head>
<body>
<div class="code">
<h2>Mã nguồn Vue:</h2>
<pre><code><div id="app">
<h1>{{ message }}</h1>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
message: 'Hello Vue!'
}
}
}).mount('#app')
</script></code></pre>
</div>
<div class="output">
<h2>Kết quả hiển thị:</h2>
<!-- Đây là nơi Vue sẽ gắn vào -->
<div id="app">
<h1>{{ message }}</h1>
</div>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
message: 'Hello Vue!'
}
}
}).mount('#app')
</script>
</body>
</html>
Giải thích:
{{ message }}
là Vue template syntax → Vue sẽ thay bằng giá trị trongdata()
createApp({...}).mount('#app')
là cách khởi tạo app Vue 3- Vue “gắn” vào thẻ
<div id="app">
và quản lý hoàn toàn nội dung bên trong
Bài tập:
- Thay đổi
message
thành"Xin chào thế giới!"
→ xem kết quả. - Thêm 1 dòng
{{ newMessage }}
nữa và truyền thêm biến vàodata()
Thảo luận