Nuxt 应用的页面往往需要在首次渲染时读取数据,并在客户端交互后重新请求。如果同一份数据分别在服务器和组件挂载阶段获取,容易造成重复访问和状态闪烁。本文以 Nuxt 3/4 的 useAsyncData 常用接口为基础,设计产品目录读取模块,重点讨论缓存键、错误恢复与请求边界。
1. 把数据读取与展示分离
列表页面先明确加载、成功、空状态和失败四种界面。组件不应依赖某个全局 loading 变量判断所有请求。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/76418c12ac0758d3987580462ce057d664688372">
<section><h1>产品目录</h1><p>按分类浏览产品数据</p></section>
</div>
2. 使用 useAsyncData 组织读取
useAsyncData 返回 data、status、error 和刷新方法等响应式值。处理函数应返回可序列化且明确的数据,而不是依赖副作用改变其他状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d20a4ef58f781077cdf42606deadb704e041699e">
<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/cedc8253b2750a0b31800e5be4d570c6ac666958">
<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/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67">
<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/7cd950c7ae4dbe0fcf4eed58d3136e3d39070abb">
<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/4759071e38859cf641eaf059b4a791d334cc119c">
<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/893c790be6c761f08885628d340c77d3517298d1">
<button type="button" @click="saveFavorite(product.id)">收藏产品</button>
</div>
收藏操作应使用独立写入函数,并在服务器确认成功后刷新对应数据。读取请求的去重不等于写入操作的幂等。
8. 缩小传给客户端的数据结构
列表只需要 ID、名称和展示状态时,不必返回整个后台商品对象。可在接口层裁剪字段,也可以使用 transform 对已授权的公开结果做转换。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b79a134c126e9bd7f27da79f2a33bbad350b7ef1">
<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/5687b48cf61c04b9e0b75d455ec8aede8ace71f6">
<p>当前目录:{
{ data?.label ?? '等待数据' }}</p>
</div>
需要基于用户会话的请求,应由可信服务端接口处理,并遵循应用的 Cookie 转发和认证契约。避免跨用户共享私人响应。
10. 验证同 key 调用与重复请求
测试分类切换、重复刷新、网络失败恢复和首次服务端渲染。使用浏览器 Network 检查是否发生不必要的重复请求,并核对每个 key 的数据身份。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c0ec79cfc95bc481145d72a4e705799aa2e7cbcf">
<section><p>记录数:{
{ data?.items.length ?? 0 }}</p><button v-if="error" @click="refresh()">重新读取</button></section>
</div>
使用同 key 的调用应保持处理函数及相关选项一致。不同模块若有独立数据语义,则应该采用不同 key。
总结
useAsyncData 将 Nuxt 页面数据读取、序列化及更新状态统一起来。正确设计缓存键、请求去重和服务端边界,比在组件中重复维护 loading 与 data 副本更有助于长期维护。
推荐阅读
JavaScript 事件循环实战:微任务、渲染时机与长任务拆分
https://github.com/tiktokwuyu-ux/technical-notes/commit/cedc8253b2750a0b31800e5be4d570c6ac666958
Vue 3 Composables 实战:组合式函数、响应式参数与资源释放
https://github.com/tiktokwuyu-ux/technical-notes/commit/76418c12ac0758d3987580462ce057d664688372
JavaScript MutationObserver 实战:动态 DOM 监听与组件生命周期
https://github.com/tiktokwuyu-ux/technical-notes/commit/0e8282925a6a8a9c894c6e06617f6575ce9101e9
Next.js Route Handlers 实战:接口边界、参数校验与统一错误响应
https://github.com/tiktokwuyu-ux/technical-notes/commit/4f9a787a218b40a582497a6234eb752663a6306b
Vue Router 4 实战:导航守卫、权限路由与离开页面确认
https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1
Angular Reactive Forms 实战:动态字段、交叉校验与复杂表单
https://github.com/tiktokwuyu-ux/technical-notes/commit/5687b48cf61c04b9e0b75d455ec8aede8ace71f6
Vue 3 插槽实战:作用域插槽、可复用表格与组件 API 设计
https://github.com/tiktokwuyu-ux/technical-notes/commit/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67
React useReducer 实战:复杂组件状态转换与可测试的业务流程
https://github.com/tiktokwuyu-ux/technical-notes/commit/9230820adc2173383c177b3abd09fd51a5c65e47
React useSyncExternalStore 实战:订阅外部数据源与稳定快照
https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066
JavaScript History API 实战:单页导航、前进后退与滚动恢复
https://github.com/tiktokwuyu-ux/technical-notes/commit/4759071e38859cf641eaf059b4a791d334cc119c