callOnce
在 SSR 或 CSR 期间,只运行给定函数或代码块一次。
此实用工具自 Nuxt v3.9 起可用。
目的
callOnce
函数旨在仅在以下情况下执行给定函数或代码块一次:
- 服务器端渲染,但不包括水合(hydration)
- 客户端导航
这对于只需要执行一次的代码很有用,例如记录事件或设置全局状态。
使用
callOnce
的默认模式是只运行代码一次。例如,如果代码在服务器上运行,它就不会在客户端再次运行。如果你在客户端多次调用 callOnce
,例如通过导航回此页面,它也不会再次运行。
app/app.vue
<script setup lang="ts">
const websiteConfig = useState('config')
await callOnce(async () => {
console.log('This will only be logged once')
websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
})
</script>
也可以在每次导航时运行,同时仍然避免初始服务器/客户端双重加载。为此,可以使用 navigation
模式。
app/app.vue
<script setup lang="ts">
const websiteConfig = useState('config')
await callOnce(async () => {
console.log('This will only be logged once and then on every client side navigation')
websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
}, { mode: 'navigation' })
</script>
navigation
模式自 Nuxt v3.15 起可用。callOnce
是一个组合式函数,旨在直接在 setup 函数、插件或路由中间件中调用,因为它需要将数据添加到 Nuxt payload 中,以避免在页面水合时在客户端重新调用该函数。类型
签名
export function callOnce (key?: string, fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>
export function callOnce (fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>
type CallOnceOptions = {
/**
* Execution mode for the callOnce function
* @default 'render'
*/
mode?: 'navigation' | 'render'
}
参数
key
:一个唯一的键,确保代码只运行一次。如果你不提供键,那么将为你生成一个在文件和callOnce
实例的行号中唯一的键。fn
:要运行一次的函数。它可以是异步的。options
:设置模式,要么在导航时重新执行 (navigation
),要么在应用程序的生命周期中只执行一次 (render
)。默认为render
。render
:在初始渲染期间(SSR 或 CSR)执行一次 - 默认模式navigation
:在初始渲染期间执行一次,并在每次后续客户端导航时执行一次