Pinia 使用實踐
在多品牌平台專案中,Pinia Store 在組件和 Composables 中的使用方式,以及 Store 之間的通訊模式。
1. 面試回答主軸
- 組件使用:使用
storeToRefs保持響應性,Actions 可以直接解構。 - Composables 組合:在 Composables 中組合多個 Store,封裝業務邏輯。
- Store 通訊:推薦在 Composable 中組合, 避免循環依賴。
2. 在組件中使用 Store
2.1 基本使用
<script setup lang="ts">
import { useAuthStore } from 'stores/authStore';
// 直接使用 store 實例
const authStore = useAuthStore();
// 訪問 state
console.log(authStore.access_token);
// 調用 action
authStore.setToptVerified(true);
// 訪問 getter
console.log(authStore.isLogin);
</script>
2.2 使用 storeToRefs 解構(重要!)
<script setup lang="ts">
import { useAuthStore } from 'stores/authStore';
import { storeToRefs } from 'pinia';
const authStore = useAuthStore();
// ❌ 錯誤:會失去響應性
const { access_token, isLogin } = authStore;
// ✅ 正確:保持響應性
const { access_token, isLogin } = storeToRefs(authStore);
// ✅ Actions 可以直接解構(不需要 storeToRefs)
const { setToptVerified } = authStore;
</script>
為什麼直接解構會失去響應性?
- Pinia 的 state 和 getters 是響應式的
- 直接解構會破壞響應式連接
storeToRefs會將每個屬性轉換為ref,保持響應性- Actions 本身不是響應式的,所以可以直接解構