Nuxt 数据获取层的一次重大重组,为 useAsyncData 和 useFetch 带来了显著改进。
虽然我们旨在保持向后兼容性,并将破坏性更改放在 experimental.granularCachedData 标志之后(默认禁用),但我们建议您在升级后彻底测试您的应用程序。如果您依赖于使用 useAsyncData 的组件卸载后缓存数据无限期可用的行为,您也可以禁用 experimental.purgeCachedData 以恢复到以前的行为。
所有使用相同键调用 useAsyncData 或 useFetch 的操作现在都共享底层的 refs,确保了应用程序的一致性
<!-- ComponentA.vue -->
<script setup>
const { data: users, pending } = useAsyncData('users', fetchUsers)
</script>
<!-- ComponentB.vue -->
<script setup>
// This will reference the same data state as ComponentA
const { data: users, status } = useAsyncData('users', fetchUsers)
// When either component refreshes the data, both will update consistently
</script>
这解决了组件可能存在数据状态不一致的各种问题。
您现在可以使用计算属性 refs、普通 refs 或 getter 函数作为键
const userId = ref('123')
const { data: user } = useAsyncData(
computed(() => `user-${userId.value}`),
() => fetchUser(userId.value)
)
// Changing the userId will automatically trigger a new data fetch
// and clean up the old data if no other components are using it
userId.value = '456'
当依赖项更改时,多个监视相同数据源的组件现在只会触发一次数据获取
// In multiple components:
const { data } = useAsyncData(
'users',
() => $fetch(`/api/users?page=${route.query.page}`),
{ watch: [() => route.query.page] }
)
// When route.query.page changes, only one fetch operation will occur
// All components using this key will update simultaneously
<NuxtTime> - 一个用于安全时间显示的新组件我们添加了一个新的 <NuxtTime> 组件用于 SSR 安全的时间显示,它解决了处理日期时的水合不匹配问题 (#31876):
<template>
<NuxtTime :datetime="Date.now()" />
</template>
该组件接受多种时间格式,并优雅地处理客户端和服务器渲染。
<NuxtErrorBoundary><NuxtErrorBoundary> 组件已转换为单文件组件,现在从组件中暴露了 error 和 clearError,并在错误插槽类型中也暴露了它们,这使您能够更好地在模板中并通过 useTemplateRef 处理错误 (#31847):
<NuxtErrorBoundary @error="handleError">
<template #error="{ error, clearError }">
<div>
<p>{{ error.message }}</p>
<button @click="clearError">Try again</button>
</div>
</template>
<!-- Content that might error -->
<MyComponent />
</NuxtErrorBoundary>
<NuxtLink> 现在接受一个 trailingSlash prop,让您对 URL 格式有更多的控制 (#31820):
<NuxtLink to="/about" trailing-slash>About</NuxtLink>
<!-- Will render <a href="/about/"> -->
您现在可以通过组件上的新 prop 直接自定义加载指示器 (#31532):
hideDelay:控制加载条隐藏前的等待时间resetDelay:控制重置加载指示器状态前的等待时间<template>
<NuxtLoadingIndicator :hide-delay="500" :reset-delay="300" />
</template>
Nuxt 文档现在作为 npm 包提供!您可以安装 @nuxt/docs 以访问用于构建文档网站的原始 markdown 和 YAML 内容 (#31353).
我们添加了一些警告,以帮助捕获常见错误
runtimeConfig.app 命名空间时的警告#31774definePageMeta 时的错误#31634模块作者会很高兴知道
experimental.enforceModuleCompatibility 允许 Nuxt 在加载不兼容的模块时抛出错误 (#31657)。它将在 Nuxt v4 中默认启用。addComponentExports 自动注册通过文件中的命名导出导出的所有组件#27155进行了一些性能改进
tinyglobby 以实现更快的 glob 文件查找#31668.data 目录,以加快构建速度#31738purgeCachedData 检查来改进摇树优化#31785我们建议升级时运行
npx nuxi@latest upgrade --dedupe
这会刷新您的 lockfile 并拉取 Nuxt 依赖的所有最新依赖项,尤其是来自 unjs 生态系统的依赖项。
衷心感谢所有参与本次发布的人。❤️