Vue 3 与 Pinia 实战:跨组件状态共享、异步 Action 和数据一致性

当一个 Vue 项目只有两三个组件时,使用 ref 和 computed 往往就足够了。但在实际后台系统中,同一个客户资料可能同时被导航栏、编辑弹窗、列表卡片和详情面板使用。如果各组件分别请求数据、保存副本,更新后很容易出现界面不一致。

Pinia 是 Vue 生态常用的状态管理方案,适合把具有明确所有权的客户端共享状态组织成 Store。本文以客户管理面板为例,讨论 Store 的边界、storeToRefs、异步 Action、并发覆盖和服务端数据的同步策略。

一、什么时候应该提取 Store

判断是否需要 Store,重点不是组件层级有多深,而是是否有多个组件需要共同读取和修改同一组业务状态。如果筛选输入只影响一个列表,继续保留组件局部状态即可;如果客户详情与多个页面共享,则可以考虑抽取 Store。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/3926a8447bf30f8faeee0029265c1c93d11ab2ab" class="customer-console">
  <header><h1>客户工作台</h1></header>
  <aside data-customer-navigation></aside>
  <main data-customer-list></main>
</div>

Store 不应成为一个无所不包的全局对象。用户身份、客户列表、界面偏好和权限策略有不同的变化周期,应按领域拆分,避免一个模块修改数据导致大量无关视图重新处理。

二、初始化 Pinia

在 Vue 3 项目入口创建 Pinia 实例,并将其安装到应用。通常一个应用共享一个 Pinia 根实例,而不是每个组件各自创建一个。

// main.ts
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
app.use(createPinia());
app.mount('#app');
<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/fbb6d3760ebeb7f5934ca1b4cb65e17959a99c7b" class="app-shell" data-layout="management">
  <nav aria-label="业务导航"></nav>
  <section data-router-content></section>
  <footer data-global-notice></footer>
</div>

在使用服务端渲染的应用中,需要格外注意请求之间的状态隔离。服务端不能随意复用一个持有用户私有状态的全局单例;Store 的创建和读取应遵守所用 SSR 框架的生命周期规范。

三、使用 Setup Store 表达领域状态

Pinia 支持 Options Store 与 Setup Store。对于已经使用 Composition API 的团队,Setup Store 可以直接复用 ref、computed 和普通函数。

// stores/customers.ts
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

type Customer = { id: string; name: string; status: 'active' | 'inactive' };

export const useCustomerStore = defineStore('customers', () => {
  const items = ref<Customer[]>([]);
  const selectedId = ref<string | null>(null);
  const loading = ref(false);
  const error = ref<string | null>(null);

  const selectedCustomer = computed(() =>
    items.value.find(item => item.id === selectedId.value) ?? null
  );
  const activeCount = computed(() =>
    items.value.filter(item => item.status === 'active').length
  );

  function selectCustomer(id: string | null) {
    selectedId.value = id;
  }

  return { items, selectedId, loading, error, selectedCustomer, activeCount, selectCustomer };
});

selectedCustomer 与 activeCount 是派生数据,不必作为新的可写状态保存。这样可以避免新增客户、更新状态时忘记同步统计结果。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/53e5d903f553f253ab1874099906c7ce1115ca11" class="customer-summary" aria-label="客户统计">
  <strong data-customer-total>总数</strong>
  <span data-customer-active>活跃客户</span>
  <span data-customer-selected>当前选中</span>
</div>

四、为什么解构 Store 要用 storeToRefs

直接把 Store 上的响应式属性解构出来,可能破坏它们与 Store 的响应式联系。使用 storeToRefs() 可以为 State 和 Getter 创建对应的 Ref;Action 仍然可以直接从 Store 中取得。

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useCustomerStore } from '@/stores/customers';

const store = useCustomerStore();
const { items, loading, selectedCustomer, activeCount } = storeToRefs(store);
const { selectCustomer } = store;
</script>

<template>
  <section>
    <p>活跃客户:{{ activeCount }}</p>
    <p v-if="loading">加载中…</p>
    <ul v-else>
      <li v-for="customer in items" :key="customer.id">
        <button type="button" @click="selectCustomer(customer.id)">
          {{ customer.name }}
        </button>
      </li>
    </ul>
    <p v-if="selectedCustomer">当前:{{ selectedCustomer.name }}</p>
  </section>
</template>

Vue 模板会自动解包 Ref,不需要在模板中写 .value。这里也保留了单一状态来源:子组件表达“选中哪个客户”,而不是自行维护另一份选中对象。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/6cebe9d84c5d6351bc8930cc6f1ada81c3a00ec6" class="customer-list-toolbar">
  <label for="customer-query">搜索客户</label>
  <input id="customer-query" type="search" autocomplete="off">
  <output data-list-count></output>
</div>

五、异步 Action 必须防止旧响应覆盖新结果

Pinia 的 Action 可以是异步函数,但 Pinia 不会自动判断哪次网络请求更新得更晚。若用户快速切换筛选条件,先发出的请求可能最后返回,从而把新列表覆盖成旧内容。

可以在 Store 内维护请求序号,只允许最近一次请求落地。网络层若支持 AbortSignal,还可以取消上一请求以减少资源消耗。

// 下面的 Action 添加到 Setup Store 内部并一起 return
let requestVersion = 0;
let controller: AbortController | null = null;

async function loadCustomers(status: 'all' | 'active' | 'inactive') {
  const version = ++requestVersion;
  controller?.abort();
  controller = new AbortController();
  loading.value = true;
  error.value = null;

  try {
    const params = new URLSearchParams({ status });
    const response = await fetch(`/api/customers?${params}`, {
      signal: controller.signal
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const result = await response.json();
    if (!Array.isArray(result)) throw new TypeError('响应格式错误');
    if (version === requestVersion) items.value = result;
  } catch (cause) {
    if (version === requestVersion && (cause as Error).name !== 'AbortError') {
      error.value = '客户列表读取失败';
    }
  } finally {
    if (version === requestVersion) {
      loading.value = false;
      controller = null;
    }
  }
}

此实现用于演示并发控制,正式项目还需对返回记录做字段校验。组件卸载时是否取消加载,取决于这份 Store 是否还被其他页面使用。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/f2d111acd6b72888df874fbc7438e31f2e28a99d" class="customer-request-state" aria-live="polite">
  <p data-loading-message>正在获取客户记录</p>
  <p data-request-error role="alert" hidden></p>
</div>

六、写操作不要只更新当前弹窗

假设编辑客户名称的弹窗保存成功,只修改弹窗里的文本,并不能保证列表和详情都更新。一个简单策略是让服务端返回正式客户对象,然后以 ID 替换 Store 中对应记录。

async function renameCustomer(id: string, name: string) {
  const response = await fetch(`/api/customers/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name })
  });
  if (!response.ok) throw new Error('保存失败');

  const saved = await response.json() as Customer;
  items.value = items.value.map(item => item.id === saved.id ? saved : item);
}

这样所有订阅同一 Store 的组件都会看到更新后的记录。如果后端可能同时修改其他字段,直接使用服务端返回的完整结果通常比根据输入字段自行拼接更可靠。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/0b62869ae733507f98582dd6f5299fba4546b373" class="customer-edit-actions">
  <button type="submit" data-save-customer>保存修改</button>
  <button type="button" data-cancel-edit>取消</button>
  <p data-save-status aria-live="polite"></p>
</div>

但如果列表由服务端分页、排序和筛选生成,某条记录更新后可能不再满足当前条件。此时局部替换不能完全反映服务端结果,保存成功后重新获取当前查询通常更准确。

七、哪些内容不适合放到 Pinia

并不是所有信息都适合长期保存在 Store。临时输入焦点、只影响一个按钮的展开状态通常仍应留在组件中;超大规模的服务器查询缓存则可以评估专用查询库。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/daeb68f09b50280de68ba5d3ac16fbea174b31a4" class="view-preferences">
  <label for="display-density">列表密度</label>
  <select id="display-density" name="density">
    <option value="comfortable">舒适</option>
    <option value="compact">紧凑</option>
  </select>
</div>

此外,不要把短期认证凭据当作普通业务状态随意持久化;浏览器存储的数据可被同源脚本访问,安全边界应由认证和服务端授权机制决定。

八、测试 Store 不必先启动整个页面

Pinia Store 的测试可以从数据转换和业务操作入手:给定两条客户记录,筛选统计是否正确;更新某一条记录后,其他记录是否保持不变;两个请求乱序返回时,最终是否保留最新筛选对应的数据。

<div id="https://github.com/tiktokwuyu-ux/TIKTOK_baike/commit/1028c5bfad355d847a88079a139802534f7f5f61" class="store-test-panel">
  <h3>状态一致性检查</h3>
  <output data-test="selection">选中记录</output>
  <output data-test="concurrent-request">并发响应</output>
  <output data-test="save-result">保存结果</output>
</div>

测试时建议为每个测试用例建立独立的 Pinia 实例,并模拟 API 的成功、失败和延迟返回。这样能够明确问题出在状态逻辑还是组件渲染,而不是依赖手工点击整个后台才能验证。

九、总结

Pinia 不是把所有变量搬到全局,而是帮助团队明确谁拥有这份状态、谁能修改它、哪些视图消费它。Setup Store 组织领域数据,storeToRefs 保持响应式解构,Action 承担异步流程和写入协调。只有再补上请求竞态、服务端权威数据与测试约束,跨组件状态共享才真正具备工程可维护性。

0
0
0
0
评论
未登录
暂无评论