Mục tiêu:
- Hiểu vấn đề của việc truyền dữ liệu giữa các component
- Học cách dùng Pinia để quản lý dữ liệu dùng chung (todo list, user info, theme…)
- Ứng dụng Pinia vào app đơn giản
Vì sao cần Pinia?
Khi dữ liệu cần chia sẻ giữa nhiều component, việc truyền qua props
hoặc emit
sẽ rối và khó kiểm soát. Lúc đó ta cần một nơi trung tâm để:
- Lưu dữ liệu
- Đọc / sửa dữ liệu từ bất kỳ component nào
Đó chính là vai trò của store trong Pinia.
Cách cài Pinia (dùng CDN):
<!-- Vue 3 -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<!-- Vue Router -->
<script src="https://unpkg.com/vue-router@4"></script>
<!-- Pinia -->
<script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
Demo: Quản lý đếm số lượng (counter) dùng Pinia
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Vue + Pinia</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
<style>
body {
font-family: Arial;
padding: 30px;
}
button {
margin-right: 10px;
}
</style>
</head>
<body>
<div id="app">
<h2>📦 Demo Pinia: Bộ đếm</h2>
<p>Giá trị hiện tại: {{ counter.count }}</p>
<button @click="counter.increment">Tăng +1</button>
<button @click="counter.decrement">Giảm -1</button>
</div>
<script>
const { createApp } = Vue;
const { createPinia, defineStore } = Pinia;
// Tạo store
const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
}
}
});
const app = createApp({
setup() {
const counter = useCounterStore();
return { counter };
}
});
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
</script>
</body>
</html>
Giải thích:
Thành phần | Ý nghĩa |
---|---|
defineStore('counter', {...}) | Tạo một store tên counter |
state | Dữ liệu toàn cục |
actions | Các hàm thay đổi dữ liệu |
useCounterStore() | Dùng store trong component |
setup() | Sử dụng Composition API để khai báo dữ liệu |
Bài tập thực hành:
- Thêm
reset()
để đặt lạicount = 0
- Tạo một
todoStore
để lưu danh sách công việc - Dùng store trong nhiều component khác nhau để đọc/ghi
todo
Tổng kết:
Bạn đã học được:
- Cách tạo và dùng Pinia store
- Biến dữ liệu thành toàn cục để component nào cũng dùng được
- Cách thao tác với state, actions
Thảo luận