Fetch 钩子
fetch 钩子用于异步获取数据。在渲染路由时于服务端调用,在导航时于客户端调用。
Nuxt >= 2.12
从 Nuxt v2.12 起,为所有 Vue 组件引入了名为 fetch 的新钩子。每当需要获取异步数据时都可以使用 fetch。fetch 在服务端渲染路由时调用,在客户端导航时调用。
在组件级别暴露 $fetchState:
-
$fetchState.pending:Boolean,可用于在fetch在_客户端_调用时显示占位符。 -
$fetchState.error:null或Error,可用于显示错误信息。 -
$fetchState.timestamp:Integer,最后一次 fetch 的时间戳,配合keep-alive缓存很有用。
如果想从模板中调用 fetch 钩子,可以这样做:
<button @click="$fetch">Refresh</button>
在组件方法中:
// 来自脚本部分的组件方法
export default {
methods: {
refresh() {
this.$fetch()
}
}
}
在 fetch 钩子内可以使用 this.$nuxt.context 访问 Nuxt context 。
选项
-
fetchOnServer:Boolean或Function(默认:true)。服务端渲染页面时调用fetch()。 -
fetchKey:String或Function(默认为组件作用域 ID 或组件名称),用于标识该组件获取结果的键(或生成唯一键的函数)(Nuxt v2.15 及以上可用)。详情请参阅 PR 。 -
fetchDelay:Integer(默认:200)。设置最小执行时间(毫秒),防止极短时间内切换画面导致闪烁。
当 fetchOnServer 为假值(false 或返回 false 的函数)时,fetch 仅在客户端调用,服务端渲染组件时 $fetchState.pending 返回 true。
<script>
export default {
data() {
return {
posts: []
}
},
async fetch() {
this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
},
fetchOnServer: false,
// 多个组件可以返回相同的 `fetchKey`,Nuxt 会分别追踪它们。
fetchKey: 'site-sidebar',
// 或者,为了更精细的控制,可以传入一个访问组件实例的函数。
// 该函数在 `created` 中调用,不能依赖已获取的数据。
fetchKey(getCounter) {
// getCounter 是一个可调用的方法,可以获取序列中的下一个数字
// 作为生成唯一 fetchKey 的结果。
return this.someOtherData + getCounter('sidebar')
}
}
</script>
有关 fetch 钩子的更多详情,请参阅数据获取 文档
Edit this page on GitHub
Updated at Tue, Apr 14, 2026