55 phút
Vue.js Fundamentals
Giới thiệu Vue.js
Vue.js là progressive framework để xây dựng giao diện người dùng.
Khởi tạo ứng dụng Vue
CDN Setup
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<button @click="count++">Count: {{ count }}</button>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
message: 'Hello Vue!',
count: 0
}
}
}).mount('#app');
</script>
</body>
</html>
Vue CLI
npm install -g @vue/cli
vue create my-project
cd my-project
npm run serve
Directives cơ bản
v-bind
<div v-bind:id="dynamicId"></div>
<!-- shorthand -->
<div :id="dynamicId"></div>
v-model
<input v-model="message" placeholder="Nhập tin nhắn">
<p>Tin nhắn: {{ message }}</p>
v-for
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
v-if, v-else
<div v-if="isVisible">Nội dung hiển thị</div>
<div v-else>Nội dung thay thế</div>
Methods và Computed
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe',
items: [
{ id: 1, name: 'Item 1', price: 100 },
{ id: 2, name: 'Item 2', price: 200 }
]
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
},
totalPrice() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
},
methods: {
addItem() {
this.items.push({
id: this.items.length + 1,
name: 'Item ' + (this.items.length + 1),
price: Math.random() * 100
});
}
}
}
Bài tập thực hành
Hãy tạo ứng dụng Todo List đơn giản với Vue.js!