⚙️ SSR 支持:天然兼容服务端渲染(SSR)场景。
import { useQuery } from'@pinia/colada'; const { state, // 包含 data、error、status 等状态对象 asyncStatus, // 异步状态(loading / error / success 等) refresh, // 手动刷新当前查询 refetch, // 重新获取(忽略缓存) // 以下为状态别名: error, // 错误对象 data, // 成功返回的数据 status, // 状态:idle / loading / success / error isLoading, // 是否正在加载 isPending, // 是否处于等待中 isPlaceholderData, // 是否为占位数据 } = useQuery({ key: ['todos'], // 查询唯一标识 query: () => fetch('/api/todos').then((res) => res.json()), // 查询函数 });动态查询
const todoId = ref(1); const { data, isLoading } = useQuery({ key: () => ['todo', todoId.value], // 依赖响应式变量动态生成 key query: () => fetch(`/api/todos/${todoId.value}`).then((res) => res.json()), }); // 堆代码 duidaima.com // todoId 变化时,useQuery 会自动重新发起请求 todoId.value = 2;动态 key 的使用场景:
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
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();动态查询
const fetchTodoById = defineQuery({ key: (id) => ['todo', id], query: (id) => fetch(`/api/todos/${id}`).then((res) => res.json()), }); // 在组件中使用 const { data, isLoading } = fetchTodoById(todoId.value);三.useMutation
import { useMutation } from'@pinia/colada'; const { mutate, // 触发变更的函数 state, // 包含 data、error、status 的状态对象 asyncStatus, // 异步状态 reset, // 重置状态 // 状态别名: 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 });总结