Nuxt 应用的页面往往需要在首次渲染时读取数据,并在客户端交互后重新请求。如果同一份数据分别在服务器和组件挂载阶段获取,容易造成重复访问和状态闪烁。本文以 Nuxt 3/4 的 useAsyncData 常用接口为基础,设计产品目录读取模块,重点讨论缓存键、错误恢复与请求边界。
1. 把数据读取与展示分离
列表页面先明确加载、成功、空状态和失败四种界面。组件不应依赖某个全局 loading 变量判断所有请求。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<section><h1>产品目录</h1><p>按分类浏览产品数据</p></section>
</div>
2. 使用 useAsyncData 组织读取
useAsyncData 返回 data、status、error 和刷新方法等响应式值。处理函数应返回可序列化且明确的数据,而不是依赖副作用改变其他状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<ul><li v-for="product in data?.items ?? []" :key="product.id">{
{ product.name }}</li></ul>
</div>
<script setup lang="ts">
type Product = { id: string; name: string };
const { data, status, error, refresh } = await useAsyncData('products', () => $fetch<{ items: Product[] }>('/api/products'));
</script>
3. 缓存键必须表达数据身份
多个调用使用相同 key 时可能共享状态,因此 key 应反映资源及参数。不同分类如果共享一个固定 key,就可能错误复用结果。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
<label>分类 <select v-model="category"><option value="all">全部</option><option value="hardware">硬件</option></select></label>
</div>
const category = ref('all');
const key = computed(() => `products:${
category.value}`);
const {
data } = await useAsyncData(key, () => $fetch('/api/products', {
query: {
category: category.value } }));
4. 为加载与错误建立独立界面
不要把 data 为 undefined 直接解释成没有记录。状态可能是尚未开始、请求中或失败。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
<p v-if="status === 'pending'" role="status">正在加载目录</p>
<p v-else-if="error" role="alert">目录读取失败</p>
<p v-else-if="status === 'success' && !data?.items.length">当前没有产品</p>
</div>
5. 使用 refresh 明确触发重新读取
管理员修改目录后,页面可以通过 refresh 获取当前 key 对应的最新结果。不要在 watchEffect 中同时反复调用 refresh 和修改其依赖。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
<button type="button" :disabled="status === 'pending'" @click="refresh()">刷新列表</button>
</div>
6. 选择适合的请求去重策略
同一个 key 短时间触发多个读取时,dedupe 可控制重复执行策略。defer 适合已有读取时复用等待,cancel 适合希望取消或替代之前读取的情况。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<p aria-live="polite">{
{ status === 'pending' ? '正在更新数据' : '当前数据已就绪' }}</p>
</div>
const result = await useAsyncData('catalog-summary', () => $fetch('/api/catalog/summary'), {
dedupe: 'defer' });
7. 避免把副作用放进数据处理函数
useAsyncData 的读取函数可能随导航或重新验证执行多次。写入订单、发送通知和增加业务计数不应放在读取处理函数里。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<button type="button" @click="saveFavorite(product.id)">收藏产品</button>
</div>
收藏操作应使用独立写入函数,并在服务器确认成功后刷新对应数据。读取请求的去重不等于写入操作的幂等。
8. 缩小传给客户端的数据结构
列表只需要 ID、名称和展示状态时,不必返回整个后台商品对象。可在接口层裁剪字段,也可以使用 transform 对已授权的公开结果做转换。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/71a691dfd4be014c98dfd53761b08a06dc9174e9">
<article v-for="item in data?.items ?? []" :key="item.id"><h3>{
{ item.name }}</h3><p>{
{ item.available ? '可用' : '暂不可用' }}</p></article>
</div>
真正的敏感字段过滤必须在服务端完成。客户端 transform 不能代替权限校验,也不能阻止接口原始响应被读取。
9. 处理服务器和浏览器的运行边界
首次页面渲染和客户端导航可能使用不同运行环境。不要在处理函数里无条件访问 window,也不要把私人服务凭据加入公开运行时配置。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/51652c9f07b7eaaab956f778f3008867ee1fe5ac">
<p>当前目录:{
{ data?.label ?? '等待数据' }}</p>
</div>
需要基于用户会话的请求,应由可信服务端接口处理,并遵循应用的 Cookie 转发和认证契约。避免跨用户共享私人响应。
10. 验证同 key 调用与重复请求
测试分类切换、重复刷新、网络失败恢复和首次服务端渲染。使用浏览器 Network 检查是否发生不必要的重复请求,并核对每个 key 的数据身份。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/031fc2b4ebe9e073ea48634b5b568ae45add3205">
<section><p>记录数:{
{ data?.items.length ?? 0 }}</p><button v-if="error" @click="refresh()">重新读取</button></section>
</div>
使用同 key 的调用应保持处理函数及相关选项一致。不同模块若有独立数据语义,则应该采用不同 key。
总结
useAsyncData 将 Nuxt 页面数据读取、序列化及更新状态统一起来。正确设计缓存键、请求去重和服务端边界,比在组件中重复维护 loading 与 data 副本更有助于长期维护。