Pinia 最強插件發(fā)布,包含九大必備功能!
前言
大家好,我是林三心,用最通俗易懂的話講最難的知識點是我的座右銘,基礎是進階的前提是我的初心~
pinia-colada 是一款基于 Pinia 的狀態(tài)管理庫插件,旨在為 Vue 應用提供強大而便捷的異步狀態(tài)管理和請求處理能力。其官方功能亮點包括:
- ?? 自動緩存:具備智能的客戶端緩存機制,支持請求去重,避免重復加載。
- ??? 異步狀態(tài)管理:輕松管理各種異步操作和狀態(tài)。
- ?? 插件系統(tǒng):提供靈活且強大的插件擴展機制。
- ? 樂觀更新:支持在請求提交前先行更新 UI,提升用戶體驗。
- ?? 合理的默認配置:內(nèi)置推薦配置,同時支持高度自定義。
- ?? 開箱即用的插件:提供一組組合式函數(shù),簡化數(shù)據(jù)獲取邏輯。
- ?? TypeScript 支持:具備完整的 TypeScript 類型定義。
- ?? 輕量體積:核心大小約 2KB,支持 Tree Shaking 優(yōu)化。
- ?? 零依賴:除 Pinia 外不依賴任何其他第三方庫。
- ?? SSR 支持:天然兼容服務端渲染(SSR)場景。
與 vue-use 等工具庫中的 useAxios 不同,pinia-colada 直接依托 Pinia Store 進行請求緩存,具備更原生的緩存管理機制。
該庫的核心是 useQuery 和 useMutation,同時還提供 defineQuery 與 defineMutation,用于在 Pinia Store 中組織查詢與變更邏輯。
useQuery
useQuery 用于處理異步數(shù)據(jù)獲取,支持緩存、加載狀態(tài)與錯誤處理,其基本返回結(jié)構如下:
import { useQuery } from'@pinia/colada';
const {
state, // 包含 data、error、status 等狀態(tài)對象
asyncStatus, // 異步狀態(tài)(loading / error / success 等)
refresh, // 手動刷新當前查詢
refetch, // 重新獲?。ê雎跃彺妫?// 以下為狀態(tài)別名:
error, // 錯誤對象
data, // 成功返回的數(shù)據(jù)
status, // 狀態(tài):idle / loading / success / error
isLoading, // 是否正在加載
isPending, // 是否處于等待中
isPlaceholderData, // 是否為占位數(shù)據(jù)
} = useQuery({
key: ['todos'], // 查詢唯一標識
query: () => fetch('/api/todos').then((res) => res.json()), // 查詢函數(shù)
});動態(tài)查詢
key 不僅可以是靜態(tài)數(shù)組,也可以是函數(shù),適用于依賴動態(tài)參數(shù)的場景:
const todoId = ref(1);
const { data, isLoading } = useQuery({
key: () => ['todo', todoId.value], // 依賴響應式變量動態(tài)生成 key
query: () => fetch(`/api/todos/${todoId.value}`).then((res) => res.json()),
});
// todoId 變化時,useQuery 會自動重新發(fā)起請求
todoId.value = 2;動態(tài) key 的使用場景:
- 適用于分頁、篩選、詳情查詢等依賴動態(tài)參數(shù)獲取數(shù)據(jù)的場景。
- key 變化時會自動觸發(fā)查詢重新執(zhí)行。
若在分頁等場景中希望保留上一頁數(shù)據(jù)作為占位,可使用 placeholderData 避免UI閃爍:
const { state } = useQuery({
key: () => ['contacts', Number(route.query.page) || 1],
query: () =>
fetch(`/api/contacts?page=${Number(route.query.page) || 1}`).then((res) => res.json()),
placeholderData: (previousData) => previousData,
})defineQuery
defineQuery 用于在 Pinia Store 中定義查詢方法,使其可在多個組件中復用。
基本用法
import { defineStore } from'pinia';
import { defineQuery } from'@pinia/colada';
exportconst useTodoStore = defineStore('todo', () => {
const fetchTodos = defineQuery({
key: ['todos'],
query: () => fetch('/api/todos').then((res) => res.json()),
});
return { fetchTodos };
});在組件中使用:
import { useTodoStore } from '@/stores/todoStore';
const todoStore = useTodoStore();
const { data, isLoading } = todoStore.fetchTodos();動態(tài)查詢
const fetchTodoById = defineQuery({
key: (id) => ['todo', id],
query: (id) => fetch(`/api/todos/${id}`).then((res) => res.json()),
});
// 在組件中使用
const { data, isLoading } = fetchTodoById(todoId.value);useMutation
useMutation 用于處理數(shù)據(jù)變更操作(如 POST、PUT、DELETE 等),提供狀態(tài)管理與提交能力。
import { useMutation } from'@pinia/colada';
const {
mutate, // 觸發(fā)變更的函數(shù)
state, // 包含 data、error、status 的狀態(tài)對象
asyncStatus, // 異步狀態(tài)
reset, // 重置狀態(tài)
// 狀態(tài)別名:
error,
data,
status,
isLoading,
isPending,
} = useMutation({
mutation: (newTodo) =>
fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo),
}).then((res) => res.json()),
});
// 提交變更
mutate({ title: 'New Todo', completed: false });defineMutation
defineMutation 用于在 Pinia Store 中定義變更操作,增強代碼組織性。
import { defineStore } from'pinia';
import { defineMutation } from'@pinia/colada';
exportconst useTodoStore = defineStore('todo', () => {
const addTodo = defineMutation({
mutation: (newTodo) =>
fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo),
}).then((res) => res.json()),
});
return { addTodo };
});在組件中使用:
import { useTodoStore } from '@/stores/todoStore';
const todoStore = useTodoStore();
const { mutate, isLoading } = todoStore.addTodo;
mutate({ title: 'New Todo', completed: false });總結(jié)
pinia-colada 通過 useQuery / defineQuery 和 useMutation / defineMutation 提供了一套完整而優(yōu)雅的異步狀態(tài)管理方案。它不僅支持靜態(tài)與動態(tài)的查詢場景,還具備緩存管理、樂觀更新、插件擴展等高級功能,顯著簡化了復雜應用中的數(shù)據(jù)加載與狀態(tài)管理邏輯。
相關鏈接:
- 官方庫:github.com/posva/pinia-colada
- 官方文檔:pinia-colada.esm.dev

























